As new to Angular(14) I am facing this issue in reactive form while trying to access the controls property of formArray in the template file although I can access other properties like value in the template, so I have a few questions:-
1 Why can I access value property but not control property in the view file and what is the reason behind it?
**The error which I am getting is -> Property 'controls' does not exist on type 'AbstractControl<any, any>'. <ng-container *ngFor="let skill of reactiveForm?.get('skills')?.controls">
After seeing the error message I changed the logic and added a condition that I thought would prevent the issue ->**
<ng-container *ngIf="reactiveForm?.get('skills')?.hasOwnProperty('controls')">
<ng-container *ngFor="let skill of reactiveForm?.get('skills')?.controls">
</ng-container>
</ng-container>
2 Even after adding the condition why am I getting the same error?
HERE IS FULL CODE.
Ts file ->
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
title = 'reactive-form';
reactiveForm!: FormGroup;
get skillsControls() {
return (this.reactiveForm.get('skills') as FormArray).controls;
}
ngOnInit() {
this.reactiveForm = new FormGroup({
// Grouping form
personalDetails: new FormGroup({
firstname: new FormControl(null, Validators.required),
lastname: new FormControl(null, Validators.required),
email: new FormControl(null, [Validators.required, Validators.email]),
}),
gender: new FormControl('male'),
country: new FormControl('india'),
hobbies: new FormControl(null),
skills: new FormArray([
new FormControl('Cricket'),
new FormControl('Football'),
new FormControl('Rugby'),
]),
});
}
onSubmit() {
console.log(this.reactiveForm);
console.log(this.reactiveForm?.get('skills'));
}
}
Template file ->
<div class="form">
<h2 id="registration">Ragistration Form</h2>
<form action="" [formGroup]="reactiveForm" (ngSubmit)="onSubmit()">
<!-- Removed other form fields... -->
<div formArrayName="skills">
<!-- Able to access value property -->
<!-- <ng-container *ngFor="let skill of reactiveForm.get('skills')?.value">
<input type="text" placeholder="add skill.." [value]="'skill'">
</ng-container> -->
<!-- Getting Error -->
<ng-container *ngIf="reactiveForm?.get('skills')?.hasOwnProperty('controls')">
<ng-container *ngFor="let skill of reactiveForm?.get('skills')?.controls">
<input type="text" placeholder="add skill.." [value]="'skill'">
</ng-container>
</ng-container>
<!-- Solved issue using getter -->
<!-- <ng-container *ngFor="let skill of skillsControls; let i = index">
<input type="text" placeholder="add skill.." [formControlName]="skill">
</ng-container> -->
</div>
<input type="submit" value="Submit" id="btn">
</form>
</div>
Wanted to understand the problem and how we could solve this (without using the getter function).