Angular - How to set values in form array of slide toogle

Viewed 237

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]}}
1 Answers

Array to set values

export class RestrainComponent implements OnInit, OnDestroy {
      validateForm!: FormGroup;
      constructor(private fb: FormBuilder) {}
      ngOnInit(): void {
              this.validateForm = this.fb.group({
                 restrainArr: this.fb.array([])
               });
              this.restrainArr.push(this.restrainListOne);
      }
  get restrainListOne(): FormGroup {
    return this.fb.group({
      name: ['', [Validators.required, Validators.maxLength(100)]],
      inhibitionSort: [''],
      status: [false],
    });
  }
 get restrainArr(): FormArray {
    return this.validateForm.get('restrainArr') as FormArray;
  }
// set value
   setRestrain(i){
    this.restrainArr.at(i).get('status').setValue(true)
  }
}
Related