Angular – How can I write a condition in interpolation?

Issue

I have a table which is being populated through the add client form. It works fine and the changes are displayed. The thing is I have a select list in which a user selects the specific source and then it is saved in ngmodel. Here is the code.

Select List

 <mat-select [(ngModel)]="model.source" name="source" placeholder="Select Source ">
      <mat-option [value]="1 ">Upwork</mat-option>
      <mat-option [value]="2 ">Refer from Friend</mat-option>
      <mat-option [value]="3 ">Other</mat-option>
    </mat-select>

Now in my table the value which displays is 1 or 2 or 3 based on the selection. I want to write something, a condition in interpolation like this.

Table Field

<ng-container matColumnDef="source">
  <mat-header-cell *matHeaderCellDef> Source </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.source ? if value is 1 : display (upwork), if value is 2 : display(refer from friend)}} </mat-cell>
</ng-container>

Some thing like this, I did like it in angularjs I am not sure about Angular

Solution

You can use nested ternary if

{{element.source == 1 ? 'upwork' : (element.source == 2 ? 'refer from friend' : '')}}

or probably better

export class MyComponent {
  sourceNames = {1: 'upwork', 2: 'refer from friend', 3: 'other' };
}
{{sourceNames[element.source]}}

Answered By – Günter Zöchbauer

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.