【问题标题】:Angular2 template driven sub form component with validation带有验证的Angular2模板驱动子表单组件
【发布时间】:2017-07-10 05:04:36
【问题描述】:

我有一个模板驱动的表单,其中包含一组输入,包含在 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 的。

请帮我弄清楚为什么我不能将子表单添加到父表单并让它使用子表单的验证。

【问题讨论】:

    标签: javascript forms validation angular typescript


    【解决方案1】:

    一种可能的解决方案可能是将控件从子组件添加到父窗体,如下所示:

    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 Example

    【讨论】:

      【解决方案2】:

      您可以使用属性绑定和@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>
        

      【讨论】:

      • 这并不能解决问题。父组件的valid 状态仍然不受子组件中的输入影响。
      • 检查修改后的
      • 那行不通。感谢您的帮助,但请尝试确保您的答案已经过测试,或者您有充分的理由相信它应该有效。
      猜你喜欢
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-09-11
      • 2017-06-27
      • 2021-01-03
      • 2016-07-14
      • 1970-01-01
      相关资源
      最近更新 更多