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?
<mat-checkbox class = "example-margin" [(ngModel)] = obj.impresora>
<label>Printer</label>
</mat-checkbox>
obj.impresora property is boolean
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.
And then inside your app.component.ts file
will not work.
TLDR: Remove ngModel if you are setting the checked through the [checked] property
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)
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
//In HTML
The above code should work fine. Mat checkbox allows you to make it checked/unchecked, disabled, set indeterminate state, do some operation onChange of the state etc. Refer API for more details.
You can either set with ngModel either with [checked] attribute. ngModel binded property should be set to 'true':
1.
2.
3.
DEMO
There are several ways you can achieve this based on the approach you take. For reactive approach, you can pass the default value to the constructor of the FormControl(import from @angular/forms)
Instead of true or false value, yes you can send variable name as well like
FormControl(this.booleanVariable)
In template driven approach you can use 1 way binding
[ngModel]="this.booleanVariable"
or 2 way binding[(ngModel)]="this.booleanVariable"
like thisYou can also use the checked directive provided by angular material and bind in similar manner