[angular] Checkbox angular material checked by default

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

This question is related to angular checkbox angular-material angular-material2

The answer is


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>

// 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.


You need to make sure the checked property to be true inside the component.ts

export class CheckboxComponent implements OnInit {
 checked = true;
}

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)

this.randomForm = new FormGroup({
      'amateur': new FormControl(false),
});

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 this

<mat-checkbox
     name="controlName"
     [(ngModel)]="booleanVariable">
     {{col.title}}
</mat-checkbox>

You can also use the checked directive provided by angular material and bind in similar manner


Make sure you have this code on you component:

export class Component {
  checked = true;
}

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)


Set this in HTML:

    <div class="modal-body " [formGroup]="Form">
        <div class="">
            <mat-checkbox formControlName="a" [disabled]="true"> Display 1</mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="b"  [disabled]="true">  Display 2 </mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="c"  [disabled]="true">  Display 3 </mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="d"  [disabled]="true">  Display 4</mat-checkbox>
        </div>
        <div class="">
            <mat-checkbox formControlName="e"  [disabled]="true"> Display 5 </mat-checkbox>
        </div>
    </div>

Changes in Ts file

this.Form = this.formBuilder.group({
a: false,
b: false,
c: false,
d: false,
e: false,
});

Conditionvalidation in Ur Business logic

if(true){
this.Form.patch(a: true);
}

this works for me in Angular 7

// in component.ts
checked: boolean = true;

changeValue(value) {
    this.checked = !value;
}

// in component.html
<mat-checkbox value="checked" (click)="changeValue(checked)" color="primary">
   some Label
</mat-checkbox>

I hope help someone ... greetings. let me know if someone have some easiest


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


Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to checkbox

Setting default checkbox value in Objective-C? Checkbox angular material checked by default Customize Bootstrap checkboxes Angular ReactiveForms: Producing an array of checkbox values? JQuery: if div is visible Angular 2 Checkbox Two Way Data Binding Launch an event when checking a checkbox in Angular2 Checkbox value true/false Angular 2: Get Values of Multiple Checked Checkboxes How to change the background color on a input checkbox with css?

Examples related to angular-material

error TS1086: An accessor cannot be declared in an ambient context in Angular 9 @angular/material/index.d.ts' is not a module How to set width of mat-table column in angular? Confirm password validation in Angular 6 Set default option in mat-select Can't bind to 'dataSource' since it isn't a known property of 'table' Checkbox angular material checked by default How to set the color of an icon in Angular Material? Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+) Styling mat-select in Angular Material

Examples related to angular-material2

Angular-Material DateTime Picker Component? How to add icon to mat-icon-button 'mat-form-field' is not a known element - Angular 5 & Material2 Angular Material: mat-select not selecting default Checkbox angular material checked by default How to set the color of an icon in Angular Material? mat-form-field must contain a MatFormFieldControl Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue Angular2 Material Dialog css, dialog size No value accessor for form control with name: 'recipient'