Mat-checkbox [checked]="false" does not work angular 6

19,810

Solution 1

The checked property is a boolean input that expects true or false

@Input() checked: boolean

https://material.angular.io/components/checkbox/api

Using [checked]="true" would result in a checked box, [checked]="false" would result in unchecked box.


The following would be how to check with FormControl

<mat-checkbox [formControl]="checkboxFormControl">Checked Using FormControl</mat-checkbox>

checkboxFormControl = new FormControl(true);

Following would be checked using FormControl inside of FormGroup

<form [formGroup]="myForm">
  <mat-checkbox formControlName="checked">Checked Using formControlName in FormGroup</mat-checkbox>
</form>

  myForm = new FormGroup({
    checked: new FormControl(true)
  })

Stackblitz

https://stackblitz.com/edit/angular-tylt6w?embed=1&file=app/checkbox-overview-example.ts

Solution 2

I think this code help you html:

 <form [formGroup]="form">
          <mat-checkbox id="Value1" class="Value1" color="primary"
                        formControlName="Value1">Value1</mat-checkbox>
        </form>
        <pre>{{form.value | json}}</pre> 

ts:

this.form = this.fb.group({
         Value1: [false],
        });
Share:
19,810

Related videos on Youtube

ssct79
Author by

ssct79

Updated on June 04, 2022

Comments

  • ssct79
    ssct79 almost 2 years

    My mat-checkbox does not change value when using the checked input property.

    <mat-checkbox [checked]="false"
                  formControlName="value1">Value1
    </mat-checkbox>
    
    • Please explain the usage of the checked input property ie: what are the different methods for passing a boolean variable to the checked Input property?

    • Are there ways to default selection using FormControl without needing to use the checked input property on the component?

    • rhavelka
      rhavelka over 5 years
      take your original code, and remove the [checked] field. The checkbox should default to true/false depending on what value1 is.
  • ssct79
    ssct79 over 5 years
    thanks for your answer but it still does not work
  • Abhishek
    Abhishek over 5 years
    @tcw9721 can tell me what happen or error is occur?. because this code is working properly on system.
  • ssct79
    ssct79 over 5 years
    I get the alert It looks like you're using ngModel on the same form field as formControlName. Support for using the ngModel input property and ngModelChange event with reactive form directives has been deprecated in Angular v6 and will be removed in Angular v7. For more information on this, see our API docs here:
  • Abhishek
    Abhishek over 5 years
    @tcw9721 if you are using ngModel on check box please remove that because reactive form and template driven two different approach in angular both rule are different. i'm share with you link that is working please check link