【发布时间】:2020-04-05 17:10:27
【问题描述】:
将 ChildComponent 表单放入父组件表单的最佳方法是什么?我们使用的是 2019 年最新的 Angular 8。以下方法经研究后无法完全发挥作用。
父组件:
ngOnInit() {
this.parentForm = this.fb.group({
childForm1: etc
})
子组件:
this.ChildForm = this.formBuilder.group({
'streetNumber': [null, [Validators.required, Validators.maxLength(32)]],
'streetType': [null, [Validators.maxLength(8)]],
'city': [null, [Validators.maxLength(32)]],
'state': [null, [Validators.maxLength(16)]],
'postalCode': [null, [Validators.maxLength(16)]],
}, { validator: atLeastOneLocationRequired })
}
方法一:
这个方法,https://itnext.io/partial-reactive-form-with-angular-components-443ca06d8419 经过严格的测试表明 ParentForm 是有效的,即使 Child Form 是无效的。这不应该发生。
ngOnInit() {
this.parent = this.fb.group({
fullName: null
})
}
formInitialized(name: string, form: FormGroup) {
this.checkoutForm.setControl(name, form);
}
方法二:
方法 2 使用 ViewChild,这是一种不好的做法。 https://davembush.github.io/attaching-an-angular-child-component-s-form-to-a-parent/
@ViewChild(ChildComponent) childComponent: ChildComponent;
And now in ngAfterViewInit() we can add the child’s FormGroup as an additional “control” and set the parent FormGroup to the parent control’s FormGroup.
ngAfterViewInit() {
this.form.addControl('childForm', this.childComponent.form);
this.childComponent.form.setParent(this.form);
}
那么 Angular 8 中最好的 Angular 官方实践是什么?
【问题讨论】:
-
我这里做了详细解答stackoverflow.com/a/59285337/2398593
-
嗨 @maxime1992 这些是父子表单,在两个不同的组件中
-
另外,尽量不用第三方库
-
“这些是父表单和子表单,在两个不同的组件中”不确定您要实现的目标然后抱歉
-
@Artportraitdesign1 也对孩子使用相同的形式
[form]="form"angular.io/guide/dynamic-form
标签: angular typescript angular-reactive-forms angular8