问题描述
我使用了 angular material("@angular/material": "7.1.0") mat-select box 然后我使用了表单控件而不是 ng 模型,现在问题是我可以't 在组件加载时设置该值.我需要将列表中的第一个值设置为 mat-select 框,我试过了,但我不能这样做.
I used angular material("@angular/material": "7.1.0") mat-select box and then i used form control instead of ng model, now the problem is i can't set the value when the component is loading. I need to set the first value to mat-select box from the list, i tried but i cant do that.
我在 stackblitz 创建了一个代码,这里是链接:https://stackblitz.com/编辑/angular-zt1a9f
I have created a code at stackblitz, here is the link: https://stackblitz.com/edit/angular-zt1a9f
请帮助我.
推荐答案
使用 compareWith
通过比较函数内部的名称来选择默认值.另请注意,我已将 value
绑定更改为 [(value)] ="animal"
.并删除了 selectedValue
.您可以通过在 formControl
中分配它来选择默认值,查看组件中的以下更改.
Use compareWith
to select the default value by comparing the name inside the compare function. Also note, I've changed value
binding to [(value)] ="animal"
. And removed selectedValue
. You select the default by assigning it in the formControl
, look below changes in the component.
<form [formGroup]="myGroup">
<mat-form-field>
<mat-select placeholder="Favorite animal" [compareWith]="compareThem" formControlName="animalControl" required >
<mat-option>--</mat-option>
<mat-option *ngFor="let animal of animals" [(value)] ="animal" >
{{animal.name}}
</mat-option>
</mat-select>
</mat-form-field>
</form>
在您的组件中,添加:
export class AppComponent {
animals = [
{name: 'Dog', sound: 'Woof!'},
{name: 'Cat', sound: 'Meow!'},
{name: 'Cow', sound: 'Moo!'},
{name: 'Fox', sound: 'Wa-pa-pa-pa-pa-pa-pow!'},
];
myGroup = new FormGroup({
animalControl: new FormControl(this.animals[1], [Validators.required]) //I'm assigining Cat by using this.animals[1], you can put any value you like as default.
});
compareThem(o1, o2): boolean{
console.log('compare with');
return o1.name === o2.name;
}
}
这篇关于加载组件时如何在angular mat-select中设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!