我正在尝试为formControl设置默认值,但似乎无法正常工作。
select-hint-error-example.ts
export class SelectHintErrorExample {
animalControl = new FormControl('', [Validators.required]);
selectFormControl = new FormControl('', Validators.required);
animals: Animal[] = [
{name: 'Dog', sound: 'Woof!'},
{name: 'Cat', sound: 'Meow!'},
{name: 'Cow', sound: 'Moo!'},
{name: 'Fox', sound: 'Wa-pa-pa-pa-pa-pa-pow!'},
];
}
select-hint-error-example.html
<h4>{{ 'FormControl: ' + (animalControl.value | json) }}</h4>
<mat-form-field>
<mat-label>Favorite animal</mat-label>
<mat-select [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>
我需要在组件中使用formControl,如何设置默认值?
Here堆栈炸弹
更新的问题结构具有更好的代码段,而不是图像
答案 0 :(得分:1)
如果使用object设置select的默认值,则必须使用compareWith函数。
select支持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;
}
答案 1 :(得分:0)
为补充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]);
另一个方法是[value]是“ 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>
答案 2 :(得分:0)
您可以分隔animalControl的声明和实例化,并在构造函数或ngOnit中设置默认值。
export class SelectHintErrorExample {
selectFormControl = new FormControl('', Validators.required);
animals: Animal[] = [
{name: 'Dog', sound: 'Woof!'},
{name: 'Cat', sound: 'Meow!'},
{name: 'Cow', sound: 'Moo!'},
{name: 'Fox', sound: 'Wa-pa-pa-pa-pa-pa-pow!'},
];
animalControl:FormControl;
constructor(){
this.animalControl = new FormControl(this.animals[2], [Validators.required]);
}
}