我在这里开始使用Todd的反应形式教程:
https://toddmotto.com/angular-dynamic-components-forms#dynamicformmodule
然后我尝试添加一些嵌套组...所以我扩展配置如下:
public config = [
{
type: 'input',
...
},
{
type: 'select',
...
},
{
type: 'group',
label: 'testgroup',
name: 'testgroup',
children: [
{
type: 'input',
label: 'test',
name: 'test',
placeholder: 'Enter your name'
}
],
}
];
然后我将我的新表单组添加到现有表单组(手动,仅用于测试):
@Component({
selector: 'app-dynamic-form',
exportAs: 'dynamicForm',
template: `
<form
class="form"
[formGroup]="form">
<ng-container
*ngFor="let field of config;"
appDynamicField
[config]="field"
[group]="form">
</ng-container>
</form>
`,
styleUrls: ['./dynamic-form.component.css']
})
export class DynamicFormComponent implements OnInit {
@Input() config: any[] = [];
public form: FormGroup;
get value() { return this.form.value; }
constructor(private _fb: FormBuilder) {}
ngOnInit() {
this.form = this.createGroup();
}
// i loop over the configuration object and create a new control for each item
private createGroup() {
const group = this._fb.group({});
this.config.forEach((control) => {
if (control.type !== 'group') {
group.addControl(control.name, this._fb.control(null));
} else {
const nested = this._fb.group({});
nested.addControl('test', this._fb.control(null));
group.addControl('testgroup', nested);
}
});
return group;
}
}
之后我添加一个新的formGroup组件:
@Component({
selector: 'app-form-group',
styleUrls: ['form-group.component.css'],
template: `
<div class="form-group" [formGroup]="group">
<label>{{ config.label }}</label>
<ng-container
*ngFor="let field of config.children"
appDynamicField
[config]="field"
[group]="form">
</ng-container>
</div>
`
})
export class FormGroupComponent {
config;
group: FormGroup;
}
并更改dynamicField指令
const components = {
input: FormInputComponent,
select: FormSelectComponent,
group: FormGroupComponent
};
@Directive({
selector: '[appDynamicField]'
})
export class DynamicFieldDirective implements OnInit {
@Input() config: any;
@Input() group: FormGroup;
component: any;
constructor(
private _resolver: ComponentFactoryResolver,
private _container: ViewContainerRef
) {}
ngOnInit() {
const component = components[this.config.type];
const factory = this._resolver.resolveComponentFactory<any>(component);
this.component = this._container.createComponent(factory);
this.component.instance.config = this.config;
this.component.instance.group = this.group;
}
}
但我无法让它正常工作 .
错误:
formGroup expects a FormGroup instance. Please pass one in.
{{form.value | json}}模型看起来不错......但似乎嵌套的组项没有正确链接到模型...输入不会更新模型 .
{ "name": "Robert", "food": "Pizza", "testgroup": { "test": null } }