1

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>
dcp3450
  • 10,959
  • 23
  • 58
  • 110

6 Answers6

4

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>
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Eliseo
  • 50,109
  • 4
  • 29
  • 67
3

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;
}
ararb78
  • 1,137
  • 5
  • 19
  • 44
2

use two way binding.

<mat-checkbox value="true" formControlName="updates" [checked]="true">Get Updates</mat-checkbox>
Hameed Syed
  • 3,939
  • 2
  • 21
  • 31
  • 1
    here is the stackblitz that I created and checked.https://stackblitz.com/edit/mat-checkbox-h3m2gx?file=app/checkbox-overview-example.html – Hameed Syed Apr 25 '19 at 05:12
  • @HameedSyed, if you use ReactiveForm NOT use [checked]. NOTE: In your stackblitz change [checked]=true by [checked]="isChecked" (but only because you're not using ReactiveForm or [(ngModel)] in your stackblitz) – Eliseo Apr 25 '19 at 06:39
1

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.

Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
  • chaning `[checked]` to `[ngModel]` fixed the issue... I don't know why – dcp3450 Apr 25 '19 at 05:22
  • @dcp3450 don't mix template driven style with reactive form style, when you use reactive forms, don't use anything related to ngModel. It will give you bugs which will be very difficult to resolve. – Ashish Ranjan Apr 25 '19 at 05:43
  • @xyz, not use an auxiliar variable, just use `this.form.get('con').value` – Eliseo Apr 25 '19 at 06:36
  • @Eliseo I don't follow, where should I use `this.form.get('con').value`? – Ashish Ranjan Apr 25 '19 at 06:40
  • in your checkBoxChecked function you can return simply this.form.get('con').value -if you want you can use `return this.form?this.form.get('con').value:false` to avoid error if this.form are not defined – Eliseo Apr 25 '19 at 07:27
  • @Eliseo yeah, But I am also using the `checkBoxChecked` property during form initialization, if you would look at the stackblitz. I will better update the full answer. – Ashish Ranjan Apr 25 '19 at 07:30
0

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]), 
  });
}
ararb78
  • 1,137
  • 5
  • 19
  • 44
0

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.

Danny Bullis
  • 3,043
  • 2
  • 29
  • 35