Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

angular - Set value of <mat-select> programmatically

I'm trying to set value of 2 fields <input matInput> abnd <mat-select> programatically. For text input everything works as expected however for the <mat-select> on the view this field is just like it would have value off 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...