Set value of programmatically

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 items’ 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>
</mat-form-field>

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)