Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined."
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Trainer Registration Form';
registrationForm: FormGroup;
get LanguagesForm() {
return this.registrationForm.get('Languages') as FormArray;
}
addLanguage() {
this.LanguagesForm.push(this.fb.control(''));
}
constructor(private fb: FormBuilder) {}
ngOnInit(){
this.registrationForm = this.fb.group({
personalDetails: this.fb.group({
name: this.fb.group({
firstName: [''],
lastName: ['']
}),
aboutYours: [''],
dob: [''],
Languages: this.fb.array([]),
wTT: ['']
})
});
}
onSubmit() {
console.log(this.registrationForm.value);
// this._registerationservice.register(this.registrationForm.value).subscribe(
// response => console.log('Success', response),
// error => console.log('Error',error)
// );
}
}
Expected Result: When the user clicks on the button "Add Language," a new input field should be created.
Actual Result: I am receiving the error message "TypeError: Cannot read property 'controls' of undefined"
app.component.html File
<div style="text-align:center">
<h1>Welcome to {{ title }}!</h1>
</div>
<mat-horizontal-stepper >
<mat-step [stepControl]="personalDetails">
<ng-template matStepLabel>Enter Personal Details</ng-template>
<div formGroupName="personalDetails">
<div formGroupName="name">
<div class="form-group">
<label>First Name : </label>
<input type="text" formControlName="firstName" class="form-control" >
</div>
<div class="form-group">
<label>Last Name : </label>
<input type="text" formControlName="lastName" class="form-control">
</div>
</div>
<div class="form-group">
<label>DOB : </label>
<input type="date" formControlName="dob" class="form-control">
</div>
<div class="form-group">
<label>About Yourself : </label>
<textarea formControlName="aboutYours" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Language(s) : </label>
<button type="button" class="btn btn-secondary btn-sm m-2" (click)="addLanguage()">Add Language</button>
<div formArrayName="Languages">
<div *ngFor="let lang of langsform.controls; let i =index;">
<input type="text" class="form-control" [formControlName]="i">
</div>
</div>
</div>
</mat-horizontal-stepper>
</form>
</div>