I got a reactive form with a form Array called enabledChannels.
ngOnInit(): void {
this.form = this._formBuilder.group({
name: [this.notificacao.name, Validators.required],
nabledChannels: this.buildChannelArray()
});
}
buildChannelArray() {
const values = this.canaisHabilitados.map(() => new FormControl(false));
return this._formBuilder.array(values, this.requiredMinCheckboxChannel(1));
}
I need to send to my api the name of my channels, so I have a array of string called canaisHabilitados.
canaisHabilitados = ['PUSH', 'SMS'];
When I submit my form, I need to send the name of my channel, so I change in my submit and it's working perfectly:
onSubmit() {
let valueSubmit = Object.assign({}, this.form.value);
valueSubmit = Object.assign(valueSubmit, {
enabledChannels: valueSubmit.enabledChannels
.map((valor, index) => (valor ? this.canaisHabilitados[index] : null))
.filter((valor) => valor !== null),
});
...
}
But, when I edit my register, I need to get the value of my formArray, as a array of boolean again so I can use it in my template HTML, to see which slide toogle is checked.
HTML
<div *ngFor="let channel of form.get('enabledChannels')?.['controls']; let i = index" formArrayName="enabledChannels">
<mat-slide-toggle (click)="toogleChannel(canaisHabilitados[i])" [formControlName]="i" [checked]="channel.value">
{{canaisHabilitados[i]}}