Peyman Kheiri
Peyman Kheiri

Reputation: 427

mat-checkbox: The checkboxes are checked by default and affect each other?

I have 7 checkboxes in my RactiveForm. This is how I am generating them using FormArray:

ts:

  weekDaysDe: string[] = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];

  taskForm: FormGroup = this.formBuilder.group({
    weekDays: this.formBuilder.array([
      this.formBuilder.control(false),
      this.formBuilder.control(false),
      this.formBuilder.control(false),
      this.formBuilder.control(false),
      this.formBuilder.control(false),
      this.formBuilder.control(false),
      this.formBuilder.control(false),
    ]),
  });


html:

      <!-- weekdays -->
      <div class="task-form-control" *ngIf="isRecurrent">
        <mat-label>Tage</mat-label>
        <div class="weekdays" formArrayName="weekDays">
          <mat-checkbox
            *ngFor="
              let weekDay of taskForm.get('weekDays').value;
              let i = index
            "
            color="primary"
            labelPosition="before"
            [formControlName]="i"
            >{{ weekDaysDe[i] }}</mat-checkbox
          >
        </div>
      </div>

The checkboxes are rendered as expected but there are two problems:

  1. They are all checked at first
  2. They check/uncheck each other. For example when I check the first one the last one also get checked

enter image description here

What have I done wrong?

Upvotes: 0

Views: 4447

Answers (1)

Chellappan வ
Chellappan வ

Reputation: 27303

In template, Use Form Array controls to iterate over with *ngFor.

Try this:

 <div class="weekdays" formArrayName="weekDays">
            <mat-checkbox *ngFor="
              let weekDay of weekDaysArray.controls;
              let i = index
            " color="primary" labelPosition="before" [formControlName]="i">{{ weekDaysDe[i] }}
            </mat-checkbox>
   </div>

Access the FormArray control with a getter method like this.

componen.ts

 get weekDaysArray() : FormArray{
    return this.taskForm.get('weekDays') as FormArray;
  }

Example

Upvotes: 2

Related Questions