有谁能告诉我如何设置以下选择的初始值?我已尝试通过我的formControl执行此操作,虽然表单中的值将是正确的,但它不会反映在视图中
HTML
<mat-form-field>
<mat-select name="animationType" formControlName="animationType"
placeholder="select animation">
<mat-option *ngFor="let type of animationTypes" [value]="type">
{{type.name}}
</mat-option>
</mat-select>
</mat-form-field>
TS
animationTypes = [
{ name: 'balloon' },
{ name: 'kite' },
{ name: 'wolf' }
];
答案 0 :(得分:0)
我发现您使用了formControlName
,因此您可以直接从TS
文件设置默认值,如下所示:
HTML:
<mat-form-field>
<mat-select name="animationType" formControlName="animationType" placeholder="select animation">
<mat-option *ngFor="let type of animationTypes" [value]="type">
{{type.name}}
</mat-option>
</mat-select>
<mat-error *ngIf="poemForm.controls.animationType.invalid">{{getErrorMessage()}}</mat-error>
</mat-form-field>
TS:
ngOnInit() {
this.poemForm.patchValue({
animationType: selectedAnimationType // Selected Value E.g. this.animationTypes[0]
});
}
答案 1 :(得分:0)
似乎我找到的唯一解决方案就是在选择上插入一个ngModel。
<mat-form-field>
<mat-select name="animationType" formControlName="animationType"
placeholder="select animation" [(ngModel)]="selectedAnimType">
<mat-option *ngFor="let type of animationTypes" [value]="type.name">
{{type.name}}
</mat-option>
</mat-select>
<mat-error *ngIf="poemForm.controls.animationType.invalid">{{getErrorMessage()}
</mat-error>
</mat-form-field>