I am encountering an issue with my forms. On the web, all my slide-toggle options are pre-checked as shown in the image provided.
I suspect that the problem lies within the patchFor(){}
function. Could someone please review my code for me?
I have attempted the following code:
ts:
homeboxsp: Package[] = [];
activeHomeboxPForm: FormGroup;
this.activeHomeboxPForm = this.fb.group({
'active': new FormControl('', Validators.required),
'homeboxpackage_id': new FormControl('', Validators.required)
});
populateFormHomeboxP() {
this.hsP.homeboxPGetAll().subscribe(
homeboxsp => {
this.homeboxsp = homeboxsp;
this.patchForm();
}
)
}
patchForm() {
this.activeHomeboxPForm.patchValue({
active: this.homeboxsp.map(x => x.active),
homeboxpackage_id: this.homeboxsp.map(x => x.homeboxpackage_id)
});
console.log(this.homeboxsp.map(x => x.active))
console.log(this.homeboxsp.map(x => x.homeboxpackage_id))
}
The console displays my values. See the imageformconsole.
Here is the HTML:
<form [formGroup]="activeHomeboxPForm" class="col s12" materialize>
<section class="example-section">
<mat-slide-toggle formControlName="active" value="active"
class="example-margin"
[color]="color" [checked]="checked"
(click)="onActiveHomeboxP(item.homeboxpackage_id, item.active)">
{{item.active}}
</mat-slide-toggle>
</section>
</form>
Could someone suggest what might be wrong with this code? Thank you.
My Code Demo: DEMO
Updated Code: ts code:
this.activeHomeboxPForm = new FormGroup({
'active': new FormControl(true, Validators.required),
'homeboxpackage_id': new FormControl('', Validators.required)
});
populateFormHomeboxP() {
this.ws.homeboxPGetAll().subscribe(
homeboxsp => {
this.homeboxsp = homeboxsp.map((homeboxspp) => {
this.activeHomeboxPForm.controls['active'].setValue(homeboxspp.active),
this.activeHomeboxPForm.controls['homeboxpackage_id'].setValue(homeboxspp.homeboxpackage_id)
console.log(homeboxspp)
console.log(homeboxspp.active)
console.log(homeboxspp.homeboxpackage_id)
return new HomeboxP(homeboxspp);
});
}
)
}
html code:
<tbody>
<tr *ngFor="let item of homeboxsp; let i=index">
<td>
<form [formGroup]="activeHomeboxPForm" class="col s12">
<section class="example-section">
<mat-slide-toggle formControlName="active" class="example-margin" [checked]="item.active === '1'"> {{item.active}}
</mat-slide-toggle>
</section>
</form>
</td>
</tr>
</tbody>
In the provided image, everything looks fine on the console, but it doesn't display correctly in the HTML. When active = 1, it should be checked and when active = 0, it should be unchecked. Any ideas on how to resolve this?