Reputation: 133
I have a problem with 2 way binding in mat-select component (angular material). In my ts file I have a option list and the binding variable (valueFromDB). Then I select value in mat-select component it's copy the value to valueFromDB variable. On another hand, On sceen load I would like to see in my mat-select component valueFromDB variable. How can I do it?
https://stackblitz.com/edit/angular-grupfc?file=app%2Fselect-value-binding-example.html
export class SelectValueBindingExample {
valueFromDB = new Option('Option2');
options = [new Option('Option1'), new Option('Option2'), new Option('Option3')];
}
export class Option{
name:string;
constructor(n:string){
this.name = n;
}
}
<mat-form-field>
<mat-select [(ngModel)]="valueFromDB" >
<mat-option>None</mat-option>
<mat-option *ngFor='let option of options' [value]='option' >{{option.name}}</mat-option>
</mat-select>
</mat-form-field>
Upvotes: 2
Views: 6949
Reputation: 73337
Your valueFromDB
has no reference to the objects in your array, therefore Angular cannot bind them. I see two options, create a reference by finding the matching value in the array, like:
ngOnInit() {
this.valueFromDB = this.options.find(x => x.name === this.valueFromDB.name)
}
or then use compareWith
:
compareFn(op1: Option, op2: Option) {
return op1.name === op2.name;
}
and in template:
<mat-select [(ngModel)]="valueFromDB" [compareWith]="compareFn">
Your StackBlitz with compareWith
: https://stackblitz.com/edit/angular-grupfc-yjl58l?file=app%2Fselect-value-binding-example.html (creating the object reference is also added but commented out)
Upvotes: 10