I am Creating Dynamic Form, using formArray. But I am getting encountered with the "TypeError: Cannot read property 'controls' of undefined"
enter code here
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 = 'Trainner 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: [''],
// lang: [''],
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: If user Click on the button "Add Language", A new Input Field should be created.
Actual Result: I am Getting "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>
<!-- <input type="text" formControlName="lang" class="form-control"> -->
<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>