1
votes

I have a form

    <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>

and in that form there is a child component <address> and I want validation on parent and child component both. I want to do it with ngForm, I know how to do it with formgroups, by passing form variable into child component but I have tried that as well but it get me an error

child component

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

1 Answers

1
votes

You need to pass form variable into child component like this

<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>

handle that variable and import ControlContainer & NgForm in child component

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;
}

Now it will handle validation for both the component parent and child.

stackblitz.com/edit/angular-uee6gk