不要在堆栈溢出时粘贴图像。
服装:
animalControl = new FormControll('Meow!', [Validators.required]);
或第二种方法:
ngOnInit() {
this.animalControl.setValue("Some new value")
}
如果使用对象设置select的默认值,则必须使用compareWith函数。
选择支持compareWith输入。 compareWith带功能其中有两个参数:option1和option2。如果给出compareWith,Angular通过函数的返回值选择选项。
component.html
<h4>{{ 'FormControl: ' + (animalControl.value | json) }}</h4>
<mat-form-field>
<mat-label>Favorite animal</mat-label>
<mat-select [compareWith]="compareFn" [formControl]="animalControl" required>
<mat-option>--</mat-option>
<mat-option *ngFor="let animal of animals" [value]="animal">
{{animal.name}}
</mat-option>
</mat-select>
<mat-error *ngIf="animalControl.hasError('required')">Please choose an animal</mat-error>
<mat-hint>{{animalControl.value?.sound}}</mat-hint>
</mat-form-field>
component.ts
compareFn(cmp1,cmp2){
return cmp1 && cmp2 ? cmp1.sound === cmp2.sound : cmp1 == cmp2;
}
为了补充Chellapan的答案,如果您不想使用compareWith,则需要放置“相同的对象”,例如:]
animalControl = new FormControl(this.animals[2], [Validators.required]); //or const animal=this.animals.find(x=>x.name=='Cow') animalControl = new FormControl(animal, [Validators.required]);
另一个方法是[值]是“ animal.name”
<mat-option *ngFor="let animal of animals" [value]="animal.name">
您可以使用
animalControl = new FormControl('Cow',[Validators.required]);
但是您需要创建一个函数
searchAnimal(name) { return name?this.animals.find(x=>x.name==name):null }
如果您想使用
<mat-hint >{{searchAnimal(animalControl.value)?.sound}}</mat-hint>