0

Here is the logic: On enter, execute the following if statement

if (!elementB.isOpen){
    elementB.open()
else {
    elementC.open()
    elementC.focus()
    elementB.close()
}

I want to use the ? conditional operator and add it after (keyup.enter):

<mat-form-field (keyup.enter)="!elementB.isOpen ? elementB.open() : elementC.open();elementC.focus();elementB.close()">

However the code above gave me an error. It seems like I cannot execute multiple lines of code with conditional operator( ? : ).

Can anyone help me with this? Thanks!

1
  • 1
    Well you can, separating each statement by a **,**. But it's not really recommended. You should keep more of your logic in TypeScript. It's more managable and unit-testable that way. Commented Oct 3, 2018 at 13:55

3 Answers 3

3

Use the component file rather than stuffing the template full of logic:

<mat-form-field (keyup.enter)="elementActions()">

In your component:

public elementActions(): void {
  if (!this.elementB.isOpen) {
    elementB.open();
  } else {
    this.elementC.open();
    this.elementC.focus();
    this.elementB.close();
  }
}

I know it's terribly mundane, but that's what the component.ts file should really be used for.

Sign up to request clarification or add additional context in comments.

1 Comment

elementB and elementC are ids of mat-select, like: <mat-select placeholder="Contact" [formControl]="contact" #elementB>. How can I access them in my.component.ts and apply functions like open(), focus()...
2

try to give else in a method,so that you can simplify the logic

<mat-form-field (keyup.enter)="!elementB.isOpen ? elementB.open() : changeElement(elementC,elementB)">

  changeElement(elementC: any, elemenB: any) :void {
        elementC.open();
        elementC.focus();
        elementB.close();
    }

2 Comments

elementB and elementC are ids of mat-select, like: <mat-select placeholder="Contact" [formControl]="contact" #elementB>. How can I access them in my.component.ts and apply functions like open(), focus()...
add elements as parameters in changeElement(elementC,elementB)
0

Wrap it around brackets

<mat-form-field (keyup.enter)="!elementB.isOpen ? (elementB.open()) : (elementC.open(),elementC.focus(),elementB.close())">

1 Comment

, is not working: Parser Error: Unexpected token ','

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.