I have a problem with my forms. In web all my slide-toggle are checked like in .image
I think that problem is in patchFor(){}
Can you look my code please?
I try this 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))
}
console show my value. imageformconsole
and 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>
Please can you suggest me what is wrong in this code? Thank you
My exp: DEMO
Update 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 console looks good, but in html doesn't display, active = 1 checked and active = 0 no checked. Please any idea how to implement?
You've got the same
formControlName
for all your slidersTry setting a unique control name
https://stackblitz.com/edit/angular-afrebm?file=app/app.component.html
Whether a slide is checked or not is defined with the
[checked]
property, so if you want your sliders to reflect theactive
property of your elements you need something likeEDIT
Working demo
Here is complete working DEMO
Actually what was done: I turned
myform
to contain all three slide-toggles and changedpatchForm
function:Note changes in template
[formGroup]="myform[i]"
Changes in myForm declaration:
And at least changes in
patchForm
: