dcp3450
dcp3450

Reputation: 11187

Material Checkbox checked property not working

mat-checkbox isn't default checked when checked property is set to true:

<mat-checkbox value="true" formControlName="updates" checked="true">Get Updates</mat-checkbox>

Upvotes: 2

Views: 24024

Answers (6)

Danny Bullis
Danny Bullis

Reputation: 3199

In Angular 10+, you can bind a FormControl to an HTML input element of type checkbox to a model in your controller.

You don't need to bind to [checked] or [(ngModel)] in your HTML code if you use pure a ReactiveForm implementation. Binding the [formControlName] directive to a FormGroup control will provide this functionality out of the box. Make sure your controls are defined in a <form> element which is bound to a FormGroup. Your HTML should resemble this:

<form [formGroup]='myForm'>
  <input type='checkbox' [formControlName]='"enabled'" />
</form>

In your controller:

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.scss']
})
export class MyFormComponent implements OnInit {
  
  public createForm: FormGroup;
  public myModel = {
    checked: false
  };

  ngOnInit() {
    this.myForm = new FormGroup({
      // value: false will uncheck the checkbox by default,
      // value: true will check the checkbox by default
      // IMPORTANT: The disabled property is REQUIRED for binding to work
      'enabled': new FormControl({
        value: this.myModel.checked, 
        disabled: false // required for model binding to work!
      })

      // this simpler form works, too:
      // 'enabled': new FormControl(this.myModel.checked)
    });
  }
}

If you use this approach, it's very important to note in the Initializing Form Controls section of the FormControl documentation that:

The following example initializes the control with a form state object. The value and disabled keys are required in this case.

// example given in documentation:
const control = new FormControl({ value: 'n/a', disabled: true });

If you attempt to initialize the FormControl as new FormControl({value: false}) without specifying the disabled property, the checkbox value will not be bound and it will render as checked by default.

If you

You can programmatically update the value of this checkbox by using the patchValue() method:

// ...in your controller...
// no need to specify disabled property here
this.myForm.patchValue({'enabled': false});

Also note that using [formControlName] and [(ngModel)] together was deprecated in Angular 6, so that approach isn't ideal since using those two directives together may get removed in the future.

Upvotes: 0

ararb78
ararb78

Reputation: 1175

I had this problem a while ago, there are several options:

  1. You can use the property [(ngModel)] = varboolean

  2. You can set the attribute [checked] = varboolean

  3. You can default the value via formcontrol in its creation:

varboolean is a declared variable of type boolean marked by default with value "true":

public varboolean: boolean = true;

<mat-checkbox value="true" formControlName="updates" [(ngModel)] = varboolean >Get Updates</mat-checkbox>

<mat-checkbox value="true" formControlName="updates" [checked] = varboolean >Get Updates</mat-checkbox>


createForm() 
{
  this.form = this.formBuilder.group({           
      updates: new FormControl(true, [Validators.nullValidator]), 
  });
}

Upvotes: 0

ararb78
ararb78

Reputation: 1175

You can set with ngModel with [checked] attribute. ngModel binded property should be set to 'true':

component.html:

<mat-checkbox class = "example" [(ngModel)] = "myModel"> 
    <label>Hello example true </label> 
</mat-checkbox>

component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'material-component-app',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css']
})

export class AppComponent {
  myModel = true;
}

Upvotes: 3

Eliseo
Eliseo

Reputation: 57939

NOT use checked. if you have used Reactive Forms then just set a value to the field

//When you create the form
this.form=new FormGroup({
   updates:new FormControl(true)
}
//Or in a function
this.form.get('updates').setValue(true)

<!--no value, no checked, just formControlName-->
<form [formGroup]="form">
   <mat-checkbox formControlName="updates" >Get Updates</mat-checkbox>
</form>

Upvotes: 4

Ashish Ranjan
Ashish Ranjan

Reputation: 12960

As far as Reactive forms are concerned, I haven't found a way to dynamically check a checkbox and update the form control's value.

Using [checked] just checks the HTML checkbox element, but doesn't affect the control.

If you have to handle the checkbox dynamically depending on a variable's value, then you can use this approach.

Have setters and getters for the variable which decides the checked state, update the form control in the setter.

Something like:

private _checkBoxChecked = false

set checkBoxChecked(val) {
  this._checkBoxChecked = val
  this.form.get('con').setValue(this.checkBoxChecked); // update your checbox control here
}

get checkBoxChecked() {
  return this._checkBoxChecked
}

ngOnInit() {
  this.form = this._fb.group({
    con: [this.checkBoxChecked]
  })
}

See an example here: https://stackblitz.com/edit/angular-hba5pt?file=src%2Fapp%2Fapp.component.ts

In the added example, it is normal input checkbox not a mat-input checkbox, but ideally this approach should work for that too.

Upvotes: 1

Hameed Syed
Hameed Syed

Reputation: 4275

use two way binding.

<mat-checkbox value="true" formControlName="updates" [checked]="true">Get Updates</mat-checkbox>

Upvotes: 2

Related Questions