如何将mat-option绑定到control?我尝试了一些类似<mat-option *ngFor="let option of control.value" [value]="option">、<mat-option *ngFor="let option of control.value['option']" [value]="option">和其他变体的东西。但还是不起作用。
<form [formGroup]="myForm">
<ng-container *ngFor="let control of myForm.controls | keyvalue">
<mat-form-field>
<mat-select formControlName="{{control.key}}">
<mat-option *ngFor="let option of options" [value]="option">
{{option.parameter}}
</mat-option>
</mat-select>
</mat-form-field>
</ng-container>
</form>TS
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
options = [{ type: "first", parameter: "first" }, { type: "first", parameter: "first" }];
secondOptions = [{ type: "second", parameter: "second " }, { type: "second", parameter: "second" }];
myForm = new FormGroup({
first: new FormControl(this.options),
second: new FormControl(this.secondOptions)
});
constructor() {
this.myForm.controls
}
}发布于 2019-10-09 10:41:28
将选项保留在FormControl之外,不要将选项设置为值,您需要处理控件之外的选项。
HTML:
<form [formGroup]="myForm">
<ng-container *ngFor="let control of myForm.controls | keyvalue">
<mat-form-field>
<mat-select formControlName="{{control.key}}">
<mat-option *ngFor="let option of options[control.key]" [value]="option">
{{option.parameter}}
</mat-option>
</mat-select>
</mat-form-field>
</ng-container>
</form>TS。注意,我们创建了一个options对象,其属性名与控件的名称相同。
options = {
first: [
{ type: "first", parameter: "first" }, { type: "first", parameter: "first" }
],
second: [
{ type: "second", parameter: "second " },
{ type: "second", parameter: "second" }
]
}
myForm = new FormGroup({
first: new FormControl(),
second: new FormControl()
});
constructor() {
this.myForm.controls
}发布于 2019-10-09 10:34:41
在我的注释之后,不应该将选项绑定到窗体控件。
相反,只需创建一个如下所示的二维数组:
groups = [
{ controlName: 'first', options : [{ type: "first", parameter: "first" }, { type: "first", parameter: "first" }] },
{ controlName: 'second', options : [{ type: "second", parameter: "second " }, { type: "second", parameter: "second" }] },
];
myForm = new FormGroup({
first: new FormControl(),
second: new FormControl()
});然后重复一遍。
<form [formGroup]="myForm">
<ng-container *ngFor="let obj of groups">
<mat-form-field>
<mat-select [formControlName]="obj.controlName">
<mat-option *ngFor="let option of obj.options | keyvalue" [value]="option">
{{ keyval.parameter }}
</mat-option>
</mat-select>
</mat-form-field>
</ng-container>
</form>https://stackoverflow.com/questions/58302022
复制相似问题