Set value of <mat-select> programmatically
Asked Answered
C

7

51

I'm trying to set the value of 2 fields <input matInput> and <mat-select> programmatically. For text input everything works as expected however for the <mat-select> on the view this field is just like it would have a value of null. But if I would call console.log(productForm.controls['category'].value it prints correct value that I set programmatically. Am I missing something?

Here is the code:

form config:

productForm = new FormGroup({
    name: new FormControl('', [
        Validators.required
    ]),
    category: new FormControl('', [
        Validators.required
    ]),
});

setting value:

ngOnInit() {
    this.productForm.controls['name'].setValue(this.product.name);
    this.productForm.controls['category'].setValue(this.product.category);
}

html:

<mat-form-field>
    <mat-select [formControlName]="'category'"
                [errorStateMatcher]="errorStateMatcher">
        <mat-option *ngFor="let category of categories" [value]="category">
            {{category.name}}
        </mat-option>
    </mat-select>
</mat-form-field>
Chaulmoogra answered 14/2, 2018 at 22:24 Comment(0)
T
78

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

Thicken answered 3/1, 2019 at 10:14 Comment(2)
This is the actual right answer. The accepted answer, by the OP, worked because OP changed the object binding to the mat-select to be the Id field, which is of a type that is a primitive type in Angular. Hence the "compareWith" works as built into Angular. If one needs to bind the mat-select to an object, then the compareWith needs to be defined. Not unlike in Java you need to implement equals and hashcode if you expect things to really work right.Regulation
this works well for me using reactive forms 😁Glacis
C
39

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);
Chaulmoogra answered 14/2, 2018 at 22:47 Comment(0)
M
14

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;
}
Monarchal answered 21/2, 2018 at 22:7 Comment(0)
M
2

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

Myrica answered 1/3, 2019 at 4:11 Comment(0)
I
0

To complete TomOw answer's, this code in template:

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

And this code in component:

 let categorySelected = this.categories.find(a => a.id == this.idCategorySelected);
      this.productForm.controls['category'].setValue(categorySelected);

Also works, because is the same reference get from same array.

I hope it helps.

Insurmountable answered 24/8, 2022 at 8:44 Comment(0)
G
0

you must set value as string!!!!

setting value:

ngOnInit() {
   this.form = this.fb.group({
       
       category: [this.product.category.toString()]
   });
}
Gun answered 16/10, 2022 at 12:35 Comment(0)
M
0

By Using FormControl we are making the logic complex by binding it in the HTML file. My Suggestion would be to use a TWO-WAY Data binding and setting the value through an Event Binding

HTML:

<mat-form-field>
    <mat-select [(value)]="categoryName" (selectionChange)="setCategoryValue(event.value)"
                [errorStateMatcher]="errorStateMatcher">
        <mat-option *ngFor="let category of categories" [value]="category.id">
            {{category.name}}
        </mat-option>
    </mat-select>
</mat-form-field>

TS.File:

setCategoryValue(categoryId) {
    this.productForm.controls['name'].setValue(this.product.name);
    const category = this.categories.filter(single => single.id === categoryId);
    this.productForm.controls['category'].setValue(category[0]);
    this.categoryName = category.name; // to display selected category name
}
Multicolor answered 22/1, 2023 at 20:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.