我有一个表格(EpisodicForm),该表格创建了一个带有孩子的季节和情节的纪录片。
我知道如何使用以下代码手动添加季节和剧集:
<pre>{{data | json}}</pre>
<div>
<form [formGroup]="episodicForm" (ngSubmit)="onEpisodicSubmit()">
<div class="form-group">
<label for="title">Title</label>
<input type="text" formControlName="title" class="form-control" [ngClass]="{ 'is-invalid': submitted && fEpisodic.title.errors }" />
<div *ngIf="submitted && fEpisodic.title.errors" class="invalid-feedback">
<div *ngIf="fEpisodic.title.errors.required">Title is required</div>
</div>
</div>
<div formArrayName="seasons">
<div *ngFor="let seas of episodicForm.get('seasons').controls; let i=index">
<legend><h3>Season {{i+1}}: </h3></legend> <span><button (click)="deleteSeason(i)">Delete Season</button></span>
<div [formGroupName]="i">
<input formControlName="seasonNumber" type="hidden" value="{{ i+1 }}" />
<div formArrayName="episodes">
<div *ngFor="let episode of seas.get('episodes').controls; let j=index">
<span><button (click)="deleteEpisode(i, j)">Delete Episode</button></span>
<div [formGroupName]="j">
<input formControlName="episodeNumber" type="hidden" value="{{ j+1 }}" />
<div class="form-group">
<label for="title">Title</label>
<input type="text" formControlName="title" class="form-control"/>
</div>
</div>
</div>
<button (click)="addNewEpisode(seas.controls.episodes)">Add new Episode</button>
</div>
</div>
</div>
</div>
<button type="button" (click)="addNewSeason()">Add Season</button>
</form>
</div>
<pre>{{episodicForm.value | json}}</pre>
有一个addNewSeason和addNewEpisode函数。注意在情节添加方式上方的html代码中:
<button (click)="addNewEpisode(seas.controls.episodes)">Add new Episode</button>
seas.controls.episodes
我想用从IMDB检索的数据填充表单,但在这种情况下,数据存储在data变量中。
我知道如何在预填充时获得seasons
控件,但我不知道如何获得剧集的控件。
ngOnInit() {
this.documentary = new Object();
this.initEpisodicForm(this.data.documentary.seasons);
}
initEpisodicForm(seasons = null) {
let title = this.documentary.title;
this.episodicForm = this.fb.group({
'title': new FormControl(title, [Validators.required]),
'seasons': this.fb.array([], Validators.required)
});
if (seasons != null) {
seasons.forEach(season => {
console.log(season);
this.addNewSeason(season);
});
}
}
addNewSeason(season = null) {
let control = <FormArray>this.episodicForm.controls.seasons;
control.push(
this.fb.group({
'seasonNumber': new FormControl(this.seasonNumber, [Validators.required]),
'episodes': this.fb.array([], Validators.required)
})
);
this.seasonNumber++;
/**
* Tried these but didnt work
*/
//console.log(<FormArray>control.controls.episodes);
//console.log(control.get('episodes'));
//this.addNewEpisode(); //Don't know what to do here
}
addNewEpisode(control) {
control.push(
this.fb.group({
'episodeNumber': new FormControl(this.episodeNumber, [Validators.required]),
'title': new FormControl(title, [Validators.required])
}));
this.episodeNumber++;
}
ps im对Angular来说还比较陌生,所以如果我没有以正确的方式进行操作,请告知。谢谢