I am trying to use an Angular Material checkbox, and set it by default as checked, but it is displayed as non-checked, what is wrong?
Make sure you have this code on you component:
export class Component {
checked = true;
}
If you are using Reactive form you can set it to default like this:
In the form model, set the value to false. So if it's checked its value will be true else false
let form = this.formBuilder.group({
is_known: [false]
})
//In HTML
<mat-checkbox matInput formControlName="is_known">Known</mat-checkbox>
For check it with ngModel, make a merge between "ngModel" and "value", Example:
<mat-checkbox [(ngModel)]="myVariable" value="1" >Subscribe</mat-checkbox>
Where, myVariable = 1
Greeting
The chosen answer does work however I wanted to make a comment that having 'ngModel' on the html tag causes the checkbox checked to not be set to true.
This occurs when you are trying to do bind using the checked property. i.e.
<mat-checkbox [checked]='var' ngModel name='some_name'></mat-checkbox>
And then inside your app.component.ts file
var = true;
will not work.
TLDR: Remove ngModel if you are setting the checked through the [checked] property
<mat-checkbox [checked]='var' name='some_name'></mat-checkbox>
You can use
<mat-checkbox [attr.checked] = "myCondition ? 'checked' : null">
if the checked attribute is set to null, it gets removed from the html tag
or you can use Vega's anwser which should work too (mine is a completion that can be usefull if you don't want to link it with ngModel)