1

I have a simple reactive form

  ngOnInit() {
    this.outerForm = this._formBuilder.group({
      firstFormGroup: this._formBuilder.group({
        nserNumber: ['', [Validators.required, Validators.pattern(this.spacePattern)]],            
      }),
      secondFormGroup: this._formBuilder.group({
        nser1Number: ['', [Validators.required, Validators.pattern(this.spacePattern)]],
        connectionRow: this._formBuilder.array([{
          connectionType: [''],
          switchHostname: ['']
        }])
      })
    });
  }

I am able to display this in UI. But I am unable to display connectionRow

<fieldset formGroupName="secondFormGroup">
      <input matInput placeholder="PID number" id='nser1Number' formControlName="nser1Number">

    <div class='formRow' *ngFor="let itemrow of connectionRow.controls; let i=index" [formGroupName]="i">
        {{i}}
    </div>
  </fieldset>

ERROR TypeError: Cannot read property 'controls' of undefined

Please help

2
  • wouldn't it be let itemrow of secondFormGroup.connectionRow ? Commented Mar 13, 2019 at 10:16
  • or even outerForm.get('secondFormGroup').get('connectionRow').controls. You can put it in a gette and just use it in you template Commented Mar 13, 2019 at 10:20

1 Answer 1

2

You missed to mention formArrayName in the template.

Update in the HTML

<fieldset formGroupName="secondFormGroup">
    <input matInput placeholder="PID number" id='nser1Number' formControlName="nser1Number">
    <div formArrayName="connectionRow">
        <div class='formRow' *ngFor="let itemrow of connectionRow.controls; let i=index" [formGroupName]="i">
            <input matInput placeholder="Tenant" formControlName="connectionType">
            <input matInput placeholder="Tenant" formControlName="switchHostname">
        </div>
    </div>
</fieldset>

And in the TS file

get connectionRow(): FormArray {
    return this.outerForm.get('secondFormGroup').get("connectionRow") as FormArray;
}
enter code here

To handle errors for each input wrap them inside a mat-form-field container. You may refer the below

<mat-form-field>
    <input matInput placeholder="Enter your email" formControlName="connectionType" required>
    <mat-error *ngIf="connectionRow.controls[i].connectionType.invalid">Your message</mat-error>
</mat-form-field>
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah that works, just can you plz tell me how I can add error field under the input?
@raju Please Mark the answer as correct if it helped you

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.