Set value of <mat-select> programatically

主宰稳场 提交于 2019-12-01 02:31:52

Solved this issue with changing the value of <mat-option> from category object to its id.

<mat-form-field>
<mat-select [formControlName]="'category'"
        [errorStateMatcher]="errorStateMatcher">
<mat-option *ngFor="let category of categories" [value]="category.id">
    {{category.name}}
</mat-option>
</mat-select>
</mat-form-field>

and setting value:

this.productForm.controls['category'].setValue(this.product.category.id);

The Angular mat-select compares by reference between that object and all the available objects in the mat-select. As a result, it fails to select the items you have set in the category field. Consequently, you have to implement the compare function to compare any of the list item's attributes as you want, and then pass this function to the [compareWith] attribute of the mat-select.
To conclude, Here is a snapshot for the final markup and script:

<mat-form-field>
<mat-select [formControlName]="category" [compareWith]="compareCategoryObjects">
    <mat-option *ngFor="let category of categories" [value]="category">
        {{category.name}}
    </mat-option>
</mat-select>

And in the component class:

compareCategoryObjects(object1: any, object2: any) {
        return object1 && object2 && object1.id == object2.id;
    }

Now it will select the item -or items if multiple select- you set for the field.

Reference:
https://github.com/angular/material2/issues/10214

Working Sample:
https://stackblitz.com/edit/angular-material2-issue-t8rp7j

The way you can achieve this using objects is to change the markup like so:

<mat-select [formControlName]="'category'"
        [errorStateMatcher]="errorStateMatcher" [compareWith]="compareFn">
<mat-option *ngFor="let category of categories" [value]="category">
    {{category.name}}
</mat-option>
</mat-select>

Then in component

compareFn(x: Category, y: Category): boolean {
return x && y ? x.id === y.id : x === y;
}

I think in here you should use FormGroup.setValue.

According to your code,

this.productForm.setValue({
name: this.product.name,
category: this.product.category
});

For more info please refer the documentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!