简体   繁体   中英

How do you set default value in mat-select within an *ngFor

I am trying to set a default value in mat-select within an *ngFor, however, accessing the element in the array from the loop is not working as wanted. Is there any similar way to this approach?

.ts file:

persons: Person[] = .. //consist of Person with name and age

.html file:

<div *ngFor="let person of persons">
    {{ person.name }}
    <mat-form-field>
    <mat-select [(value)]="person.age">
         <mat-option value="10-20">10-20</mat-option>
         <mat-option value="20-30">20-30</mat-option>
    </mat-select>
    </mat-form-field>
</div>

To set a default value, you need to populate your array with a value assigned to each object's age property. Then mat-select [(value)] binding can set the matching value as default.

Example ( Stackblitz demo ):

export class AppComponent {
  persons = [
    {
      name: 'John Smith',
      age: '30-40'
    },
    {
      name: 'Patrick Stewart',
      age: '10-20'
    }
    ,
    {
      name: 'Peter Parker',
      age: '20-30'
    }
  ]
}

If your array is dynamic, you can run a loop to assign a default value to each element as well.

ngOnInit() {
  this.persons.forEach(item => item.age = '10-20'); // set the default age you want

}

html:

<div *ngFor="let person of persons">
  {{ person.name }}
  <mat-form-field>
    <mat-select [(value)]="person.age">
      <mat-option value="10-20">10-20</mat-option>
      <mat-option value="20-30">20-30</mat-option>
      <mat-option value="30-40">30-40</mat-option>
    </mat-select>
  </mat-form-field>
</div>

Result:

在此处输入图像描述

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