ngForm中带有验证和子组件(角度6)

时间:2019-06-05 17:42:23

标签: angular

我有一个表格

    <form #basic="ngForm">
  <div>
    <label>Firstname:</label>
    <input type="text" name="firstName" ngModel required>
  </div>
  <div>
    <label>Lastname:</label>
    <input type="text" name="lastName" ngModel>
  </div>
  <address ></address>
</form>

,并且以这种形式存在一个子组件<address>,我想同时验证父组件和子组件。我想用ngForm来做到这一点,我知道如何通过将form变量传递给子组件来使用formgroups来做到这一点,但是我也尝试过这样做,但它给我一个错误

子组件

import { Component, Input } from '@angular/core';


@Component({
  selector: 'address',
  template: `

      <div>
        <label>Zip:</label>
        <input [ngClass]="{error: (basic.submitted)}" type="text" name="zip" ngModel>
      </div>
      <div>
        <label>Street:</label>
        <input type="text" name="street" ngModel required>
      </div>
      <div>
        <label>City:</label>
        <input type="text" name="city" ngModel>
      </div>

  `,

})
export class AddressComponent  {

}

1 个答案:

答案 0 :(得分:0)

您需要像这样将表单变量传递到子组件中

<form #basic="ngForm">
  <div>
    <label>Firstname:</label>
    <input type="text" name="firstName" ngModel required>
  </div>
  <div>
    <label>Lastname:</label>
    <input type="text" name="lastName" ngModel>
  </div>
  <address [basic]="basic"></address>
</form>

处理该变量并在子组件中导入ControlContainer和NgForm

import { Component, Input } from '@angular/core';
import { ControlContainer, NgForm } from '@angular/forms';

@Component({
  selector: 'address',
  template: `

      <div>
        <label>Zip:</label>
        <input [ngClass]="{error: (basic.submitted)}" type="text" name="zip" ngModel>
      </div>
      <div>
        <label>Street:</label>
        <input type="text" name="street" ngModel required>
      </div>
      <div>
        <label>City:</label>
        <input type="text" name="city" ngModel>
      </div>

  `,
  viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
export class AddressComponent  {
  @Input() basic;
}

现在它将处理父级和子级组件的验证。

stackblitz.com/edit/angular-uee6gk