Reputation: 301
Actually am trying to apply reactive forms approach in my project here in my project i have to add a Add Season Button and when button is clicked then a new formGroup is added with one form Control i.e season and one FormArray i.e episodes so that means episodes is created Dynamically now i want to add some more formGroup in episodes but am unable to figure out how to do that here what i have done so far:
export class AddContentsComponent implements OnInit, AfterViewChecked {
count = 0
episodes = []
ContentForm: FormGroup
constructor() { }
ngOnInit() {
this.ContentForm = new FormGroup({
'title': new FormControl(null, Validators.required),
'desc': new FormControl(null, Validators.required),
'image_url': new FormControl(null, Validators.required),
'subtitle_url': new FormControl(null, Validators.required),
'url': new FormControl(null, Validators.required),
'episodes': new FormArray([]),
'seasons': new FormArray([])
})
}
onSubmit() {
console.log(this.ContentForm)
}
addSeasons() {
while ((<FormArray>this.ContentForm.get('episodes')).length) {
console.log('ok');
(<FormArray>this.ContentForm.get('episodes')).removeAt((<FormArray>this.ContentForm.get('episodes')).length - 1);
}
(this.ContentForm.get('seasons') as any).push(new FormGroup({
'season': new FormControl(null),
'episodes': new FormArray([]) //here am add a dynamic formArray
}))
}
DeleteSeason(index) {
(<FormArray>this.ContentForm.get('seasons')).removeAt(index)
}
AddEpisodesInSeasons(index) {
(<FormArray>this.ContentForm.get('seasons')) //now here i want to push new FormGroup to **episodes**
}
}
https://stackblitz.com/edit/angular-ndnstv for more..
Upvotes: 0
Views: 515
Reputation: 27303
Pass selected seasons FormGroup index from html like this and add more formGroup or control as per your need.
Try this:
component.html
<button type ='button' (click) = "AddEpisodesInSeasons(i)">{{'Add Episode In Season '+(i+1)}} </button>
component.ts
AddEpisodesInSeasons(i){
((this.ContentsForm.get('seasons') as FormArray).at(i).get('episodes') as FormArray).push( // here add more as you expected);
}
Upvotes: 1