我使用了有角的材料(“@角度/材料": "7.1.0") mat-select box,然后我使用表单控件而不是 ng model,现在的问题是我无法在组件加载时设置值。我需要将第一个值设置为列表中的 mat-select box,我尝试过,但我做不到。
我在 stackblitz 创建了一个代码,链接如下:https://stackblitz.com/edit/angular-zt1a9f https://stackblitz.com/edit/angular-zt1a9f
请帮助我。
Use compareWith
通过比较比较函数内的名称来选择默认值。另请注意,我已经改变了value
绑定到[(value)] ="animal"
。并删除了selectedValue
。您可以通过在formControl
,看看下面组件的变化。
<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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)