【发布时间】:2018-07-15 20:58:48
【问题描述】:
TL、DR;
当子控件集合不是FormArray时,怎么渲染?
// 'foo', 'bar' and 'baz' are actually names chosen by the user.
// and are *not* known ahead-of-time.
let form = this.fb.group({
fields: this.fb.group({
foo: this.fb.control(''),
bar: this.fb.control(''),
baz: this.fb.control('')
})
});
我将FormGroup 用于fields,因为value 属性产生的JSON 表示必须是object 而不是array。
如果没有*ngFor,fields 怎么能被渲染——因为fields 是不可迭代的,它不会工作。
细节;
我想呈现属于Angular Form 的一组子控件,但不是在FormArray 中。
// Use FromBuilder to create the form.
constructor(private readonly fb: FormBuilder) { }
表单必须表示一个由 fields 组成的结构,其中包含键/值对:
// Create the form with no/empty fields to start.
let form = this.fb.group({
fields: this.fb.group({})
});
我不知道fields 中将存在多少子控件 - 它们将通过用户操作添加。
此时,fields 通常是 FormArray,但我必须使用 FormGroup,因为来自 value 表单的表示必须是 JSON object 而不是 JSON @ 987654344@.
在应用加载后的某个时间点,子控件使用addControl 添加到fields。控件名称实际上由用户选择。
为简单起见,我在这里将它们硬编码为foo、bar 和baz:
const fields = form.get('fields');
const foo = new FormControl('');
fields.addControl('foo', foo);
const bar = new FormControl('');
fields.addControl('bar', bar);
...
const baz = new FormControl('');
fields.addControl('baz', baz);
理想情况下我会使用*ngFor,但由于controls 不可迭代,这将不起作用:
<ng-container [formGroup]="form">
<ng-container formGroupName="fields">
<mat-form-field *ngFor="let f of form.get('fields').controls">
<input matInput ...>
</mat-form-field>
</ng-container>
</ng-container>
另外,我不知道fields 中的任何子控件的名称 - 因为如前所述,新添加的控件的名称实际上是由用户选择的。
【问题讨论】:
标签: javascript angular angular-material