PremKumar
PremKumar

Reputation: 1354

Accessing form Array values to display Mat Error

FormGroup

this.locationForm = this.formBuilder.group({
          locationName: new FormControl(null, Validators.required),
          locationURL: new FormControl(null, Validators.required),
          workTiming: this.formBuilder.array([
            this.formBuilder.group({
              beginTime: new FormControl(null,Validators.required),
            })
          ])
        })

HTML CODE:

<div formArrayName="workTiming" >
         <div *ngFor="let item of workTiming.controls;                  
                      let pointIndex=index" [formGroupName]="pointIndex">
            <div class="container">
            <mat-form-field class="responsive">
                <input type="time" required formControlName="beginTime" matInput placeholder="Begin Time">
                <mat-error *ngIf="workTiming.get('beginTime').hasError('required')"> Enter begin time </mat-error>
            </mat-form-field>
          </div>
      </div>
    </div>

I need some help on how to access the formControl name of 'beginTime' inside mat-error, since i'm using the formArray, I'm not sure on how to access it. If I give like in the code I get the error as follows

ERROR TypeError: Cannot read property 'hasError' of null

Upvotes: 3

Views: 5712

Answers (3)

allwiine
allwiine

Reputation: 31

Can be writtern as

<mat-error *ngIf="item.get('beginTime').errors?.required"> Enter begin time </mat-error>

Upvotes: 0

PremKumar
PremKumar

Reputation: 1354

Thanks for trying, I found the solution with the following code:

<mat-error *ngIf="workTiming.controls[pointIndex].get('beginTime').hasError('required')"> Enter begin time </mat-error>

Upvotes: 6

Maihan Nijat
Maihan Nijat

Reputation: 9344

You are trying to access the nested form directly which is not available for outside context. Access the nested form through parent form same like you access JS object elements:

<mat-error *ngIf="locationForm.get('workTiming.beginTime').hasError('required')"> 
  Enter begin time 
</mat-error>

Upvotes: 0

Related Questions