簡體   English   中英

Angular2模板驅動的子表單組件,帶有驗證

[英]Angular2 template driven sub form component with validation

我有一個模板驅動的表單,其中包含一個ngFor包含的一組輸入。

我試圖將重復的'子組'分成它自己的子組件,但是我很難讓父ngForm包含子組件中包含的驗證。

這是我所說的簡化版本:

父模板

<form #parentForm="ngForm">
    <input name="firstName" ngModel required>
    <input name="lastName" ngModel required>

    <child-component *ngFor="let child of children;"></child-component>
</form>

兒童模板

<div>
    <input name="foo" required ngModel>
    <input name="bar" required ngModel>
</div>

我無法讓父母表格接受required的兒童輸入。 我嘗試讓孩子處於自己的形式,並將#parentForm實例傳遞給孩子,並讓孩子調用:

this.parentForm.addFormGroup(this.childForm.form)

但這仍然行不通。

我也有孩子這樣做,反過來父母獲取子表單的ContentChildren並將每個子表單添加到表單,但仍然驗證不起作用。

我知道我可以讓子組件實現ControlValueAccessor但是我需要實現一個自定義驗證器,我不想這樣做,因為驗證都不是新的,只是required它。

請幫我弄清楚為什么我不能向父母添加子表單並讓它使用孩子的驗證。

一種可能的解決方案可能是從子組件到父組件的添加控件,如下所示:

child.component.ts

@Component({
  selector: 'child-component',
  template: `
   <div>
    <input name="foo" required ngModel>
    <input name="bar" required ngModel>
  </div>
  `
})
export class ChildComponent {
  @ViewChildren(NgModel) controls: QueryList<NgModel>;

  constructor(private parentForm: NgForm) { }

  ngAfterViewInit() {
    this.controls.forEach((control: NgModel) => {
      this.parentForm.addControl(control);
    });
  }
}

Plunker示例

你可以使用屬性綁定和@Input來解決你的問題

<form #parentForm="ngForm">
    <input name="firstName" ngModel required>
    <input name="lastName" ngModel required>

    <child-component #parentForm.childForm="ngForm" [children]="children"></child-component>
</form>

在你的

  1. 將輸入變量聲明為

     @Input() children:any[]=[]; 
  2. 修改模板如下

     <div *ngFor="let child of children;"> <input name="foo" required [(ngModel)]="child.foo"/> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM