angularangular-materialangular-ng-ifmat-selectmat-option

ngIf condition on mat-option is not getting executed


I have 2 mat-options. 1 for loading items from backend and another to display None.

<mat-form-field id="Dropdown">
    <mat-select id="ddlabel" placeholder="{{'DDLabel' | translate}}" [(value)]="selecteditem" (selectionChange)="changeitem($event)">
      <mat-option class="items-toload" [value]="item" *ngFor="let item of dditems">{{ item }}</mat-option>
      <mat-option *ngIf="isitemSelected()" class="items-toload">{{'ItemNone'  | translate}}</mat-option>
    </mat-select>
</mat-form-field>

I would want to display None(second mat-option) only when item (from first mat-option) is selected.

isitemSelected() {
    if (this.selecteditem != '') {
      return true;
    }
    return false;
  }

But this function is not getting called, so always None option is availble in the UI. please help in understanding how this is not called.

I have added an alert to isitemselected() and noticed that this is not being called. I tried using variable and setting that to true when item is selected in changeitem($event), that is always not working.


Solution

  • You don't need to call function in *ngIf condition. Please add below condition in your html directly.

    *ngIf="selecteditem && selecteditem != ''"

    <mat-option *ngIf="selecteditem && selecteditem != ''" class="items-toload">{{'ItemNone'  | translate}}</mat-option>