Reputation: 4993
I have tried to set the selected value of a Mat Select using typescript. I have the following code
<mat-form-field>
<mat-select formControlName="students" multiple>
<mat-option [value]="item.studentId"
*ngFor="let item of listOfStudents" >
{{item.name}}
</mat-option>
</mat-select>
</mat-form-field>
Typescript
this.studentService.getStudents().pipe(
takeUntil(componentDestroyed(this))
).subscribe(response => {
this.listOfStudents = _.orderBy(response, 'name', 'asc');
const selectedStudentsData = this.listOfStudents.filter(student=> Number(student['studentId']===101)|| Number(student['studentId']===102));
this.studentForm.controls['students'] = new FormControl(selectedStudentsData);
}
);
But it is not working. How to programmatically set selected values in Mat Select?
Upvotes: 2
Views: 7198
Reputation: 3604
Filter returns an array not element. And for updating values, you do not need to create a new instance of FormControl
const selectedStudentsData = this.listOfStudents
.filter(student => Number(student['studentId']===101) || Number(student['studentId']===102));
// Use setValue method to set the value
this.studentForm.controls['students'].setValue(selectedStudentsData);
// And finally validate the form
this.studentForm.updateValueAndValidity()
Upvotes: 2