I'm facing an issue with my Angular 8 edit form that utilizes a form array. When I navigate to the page, the form array is not populated with values as expected. Can anyone help me identify and solve this problem?
ngOnInit(): void {
// Fetching data from route
this.courseExam = this.activeRoute.snapshot.data['exams']['exams']['records'];
this.questions = this.activeRoute.snapshot.data['question']['question']["result"];
this.questionsOld = this.activeRoute.snapshot.data['question']['question']["result"];
console.log(this.questions)
this.createForm();
}
createForm(): void {
// Creating the form group
this.editQuestionFG = new FormGroup({
title: new FormControl(this.questions.title, Validators.required),
courseExamId: new FormControl(this.questions.courseExamId, Validators.required),
courseOptions: this._formBuilder.array([])
});
this.setValue(this.questions.courseOptions);
}
createItem(): FormGroup {
return this._formBuilder.group({
optionTitle: new FormControl('', Validators.required),
isCorrect: new FormControl(false, Validators.required)
});
}
setValue(item: Options[]) {
for (let x of item) {
this.editQuestionFG.controls['courseOptions'].setValue({
isCorrect: x.isCorrect,
optionTitle: x.optionTitle
})
}
}
html :
<div class="answer col-lg-12 kt-margin-bottom-20-mobile">
<div formArrayName="courseOptions" class="row m-auto"
*ngFor="let project of editQuestionFG.get('courseOptions').controls; let i = index">
<ng-container [formGroupName]="i">
<div class="col-lg-1 kt-margin-bottom-20-mobile icon remove text-center">
<label (click)="deleteItem(i)"><i class="la la-trash"></i></label>
</div>
<div class="col-lg-8 kt-margin-bottom-20-mobile">
<mat-form-field class="mat-form-field-fluid" appearance="outline">
<mat-label>{{'GENERAL.TITLE' | translate}} *</mat-label>
<input matInput formControlName="optionTitle"
[placeholder]="'GENERAL.TITLE' | translate">
</mat-form-field>
</div>
<div class="col-lg-3 kt-margin-bottom-20-mobile icon">
<mat-radio-group name="radp" aria-label="Select an option"
formControlName="isCorrect">
<mat-radio-button value='true'>صحیح</mat-radio-button>
</mat-radio-group>
</div>
</ng-container>
</div>
<div class="add-Item">
<button (click)="AddItems()" mat-raised-button type="button"
color="accent">{{'COURSE_QUESTION.ADD_NEW_OPTION' |translate}}</button>
</div>
</div>
Still struggling with this issue. Any insights on how I can resolve it would be greatly appreciated.