Search code examples
angularangular6angular-reactive-formsangular7angular-forms

Angular reactive form - I want to get a form property and check if its dirty and pristine


Angular reactive form - I want to get a form property and check if its dirty and pristine.

Tech: angular 7 and reactive forms.

My form:

 <form class="flex flex-wrap col-12" [formGroup]="form" (ngSubmit)="submit()">

  <input type="text" placeholder="Company Name*" formControlName="companyName" class="col-12 field">

  <div formGroupName="address" class="col-12 mb1">

      <input class="col-12 field field-google" type="text" placeholder="Your Location*" id="Location" [options]='options' formControlName="addressLine1">

  </div>
</form>

I want form.address.addressLine1 and form.companyName checked to see if they are dirty and pristine in the html so I can show an error message.

Current attempt:

<p *ngIf="form.address.addressLine1.dirty">Error....</p>

Solution

  • When using a FormGroup you can access the children using the controls property. Which is a map.

    <p *ngIf="form.controls['address'].controls['addressLine1'].dirty">Error....</p>
    

    You have two nested groups. So you have to use controls twice.

    https://angular.io/api/forms/FormGroup#controls