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?
// in component.ts
checked: boolean = true;
indeterminate:boolean = false;
disabled:boolean = false;
label:string;
onCheck() {
this.label = this.checked?'ON':'OFF';
}
// in component.html`enter code here`
<mat-checkbox class="example-margin" [color]="primary" [(ngModel)]="checked" [(indeterminate)]="indeterminate" [labelPosition]="after" [disabled]="disabled" (change)="onCheck()">
{{label}}
</mat-checkbox>
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.
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>
You need to make sure the checked
property to be true inside the component.ts
export class CheckboxComponent implements OnInit {
checked = true;
}
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