I am trying to create a dynamic form to add actors to games in my angular website, but when I load in the page I get the following errors:
The second error happens on all input fields for the dynamic form part.
export class GameAddComponent implements OnInit {
form: FormGroup;
constructor(
private gameService: GameService,
private formBuilder: FormBuilder,
private router: Router
) {
this.form = this.formBuilder.group({
name: '',
description: '',
price: '',
category: '',
image: '',
releaseDate: '',
actors: this.formBuilder.array([
this.formBuilder.control({
name: '',
isMale: '',
birthDay: '',
})
]),
});
}
get actors() {
return this.form.get('actors') as FormArray;
}
onSubmit(): void {
const values: Partial<Game> = {
...this.form.value,
};
console.log(this.form.value);
this.gameService.addGame(values).subscribe();
this.router.navigateByUrl('/games');
}
addField() {
this.actors.push(this.formBuilder.control);
}
ngOnInit(): void {}
}
<div >
<form id="contactForm" [formGroup]="form" (ngSubmit)="onSubmit()">
<!--normal working input here-->
<!--below is the dynamic form-->
<i (click)="addField()"></i>
<div *ngFor="let actor of actors.controls">
<h2>Acteur</h2>
<div >
<div >
<input
id="naam"
type="text"
placeholder="Naam"
formControlName="name"
/>
<label for="name">Naam</label>
</div>
<div >
<select
aria-label="Default select example"
formControlName="isMale"
>
<option value="0">Vrouw</option>
<option value="1">Man</option>
</select>
<label for="name">Geslacht</label>
</div>
<div >
<label for="birthDay" >GeboorteDatum:</label>
<input type="date" id="birthDay" formControlName="birthDay" />
</div>
</div>
</div>
<div >
<button id="submitButton" type="submit">
Aanmaken
</button>
</div>
</form>
</div>
When I submit the form, the data from the dynamic part is not saved, so I'd guess it's because it can't find the properties in the formbuilder
Any help would be greatly appreciated!
CodePudding user response:
You created a single control here, which holds an object with 3 properties
this.formBuilder.control({
name: '',
isMale: '',
birthDay: '',
})
But your template tries to access those properties as formcontrols
<input
id="naam"
type="text"
placeholder="Naam"
formControlName="name"
/>
<select
aria-label="Default select example"
formControlName="isMale"
>
<div >
<label for="birthDay" >GeboorteDatum:</label>
<input type="date" id="birthDay" formControlName="birthDay" />
</div>
--> I believe you actually want another FormGroup here
this.formBuilder.group({
name: '',
isMale: '',
birthDay: '',
})
CodePudding user response:
I followed the following tutorial and got my application working, https://www.tektutorialshub.com/angular/nested-formarray-example-add-form-fields-dynamically/