使用mat-select和formControl设置默认值

问题描述 投票:-1回答:3

我正在尝试为formControl设置默认值,但似乎无法正常工作。

enter image description here

enter image description here

我需要在组件中使用formControl,如何设置默认值?

Here the stackbliz

angular angular-material
3个回答
0
投票

不要在堆栈溢出时粘贴图像。

服装:

animalControl = new FormControll('Meow!', [Validators.required]);

或第二种方法:

ngOnInit() {
this.animalControl.setValue("Some new value")
}

0
投票

如果使用对象设置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;
  }

Forked Example

Reference


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]);

另一个方法是[值]是“ 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>
© www.soinside.com 2019 - 2024. All rights reserved.