3

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

3 Answers 3

6

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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>

1 Comment

Thank you, but the above answer doesn't work as expected. It worked with the following code: <mat-error *ngIf="workTiming.controls[pointIndex].get('beginTime').hasError('required')"> Enter begin time </mat-error>
0

Can be writtern as

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.