简体   繁体   中英

Angular Material : Display empty option(None) in Mat-Select on initial page load when value is null

Need to display the empty (None) option in Material Select element when the item is null.

    <mat-label>Status</mat-label>
    <mat-select formControlName="statusId">

        <mat-option>None</mat-option>

        <mat-option *ngFor="let item of statuses" [value]="item.id">
             {{ item.name }}
        </mat-option>
    </mat-select>
</mat-form-field>```

As seen in above snippet I need to display the "None" option selected by default when the page loads.

StackBlitz So, you can add a empty value to the None option.

 <mat-select [formControl]="foodControl" name="food">
      <mat-option value="">None</mat-option>
      <mat-option *ngFor="let food of foods" [value]="food.value">
        {{food.viewValue}}
      </mat-option>
    </mat-select>

And, in the ts, you can initialize the control with empty value like this foodControl = new FormControl('');

same thing can be done with ngModel as well. (included in the StackBlitz)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM