Angular (4.x.x) Material CheckBox Component (mat-checkbox) : [checked] not working

Viewed 7797

How this is possible????

See this:

<div class="col-lg-1 check-field">
    <mat-checkbox color="primary"
                  [checked]="true"
                  formControlName="flagRimb">Rimb.
    </mat-checkbox>
</div>

I've put the true value on checked and still not seeing the mat-checkbox checked when component is loaded!! incredible!!!

The only thing that can disturb the behavior is the formControl, there is it:

     return this._formBuilder.group({
        [...],
        flagAdd : ['',Validators.required],
        [...]
    });

The formControlName is there because I need to set checkbox value relative to a model.value given by http rest call, but even with a default value set to true that's not working !!

It seems from the console that the exploded material html that generate the don't inherit checked property from <_<.

Any idea? Thanks in advance!!

EDIT 1 : USED checked INSTEAD [checked]

enter image description here

3 Answers

I believe you need to use ngModel to get this to work

<mat-checkbox [(ngModel)]="someValue">
</mat-checkbox>

someValue will be true (checked) or false (unchecked)

Alternative answer with FormControl:

  1. formControlName="flagRimb" This name needs to match what is defined in the formBuilder.group
  2. true must be passed in the parameter list for the FormControl flagRimb
  3. Validation for checkboxes should be done with Validators.requiredTrue vs plain .required

Component.html

<div class="col-lg-1 check-field">
    <mat-checkbox color="primary"
                  [checked]="true"
                  formControlName="flagRimb">Rimb.
    </mat-checkbox>
</div>

Component.ts

return this._formBuilder.group({
  [...],
  flagRimb : [true, Validators.requiredTrue],
  [...]
});

Replace this

[checked]="true"

with

[checked]="true" OR checked="true"

Related