相关疑难解决方法(0)

Angular 在父组件嵌套表单中使用子组件表单

将子组件表单放入父组件表单的最佳方法是什么?我们使用的是 2019 年最新的 Angular 8。经过研究,以下方法不能完全奏效。

父组件:

 ngOnInit() {
    this.parentForm = this.fb.group({
       childForm1: etc
    })
Run Code Online (Sandbox Code Playgroud)

子组件:

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 })
Run Code Online (Sandbox Code Playgroud)

}

方法一:

这个方法,https: //itnext.io/partial-reactive-form-with-angular-components-443ca06d8419 经过严格测试表明 ParentForm 有效,即使 Child Form 无效。这不应该发生。

ngOnInit() {
  this.parent = this.fb.group({
    fullName: null
  })
Run Code Online (Sandbox Code Playgroud)

}

formInitialized(name: string, form: FormGroup) {
  this.checkoutForm.setControl(name, form);
}
Run Code Online (Sandbox Code Playgroud)

方法二:

方法 2 使用 ViewChild,这是听力不好的做法。 https://davembush.github.io/attaching-an-angular-child-component-s-form-to-a-parent/

@ViewChild(ChildComponent) childComponent: ChildComponent;

And now in ngAfterViewInit() …
Run Code Online (Sandbox Code Playgroud)

typescript angular angular-reactive-forms angular8

5
推荐指数
1
解决办法
7925
查看次数