8

I've got a problem with the mat-checkbox from angular material. I've given the checkbox an ID like this:

<mat-checkbox class="toolbar-checkbox" id="myCheckbox">
    MyCheckbox
</mat-checkbox>

After that I'm trying to something with this element like this:

(<MatCheckbox>document.getElementById('myCheckbox')).checked = true;

But unfortunally I'm getting this error:

TS2352: Type 'HTMLElement' cannot be converted to type 'MatCheckbox'. 
Property '_changeDetectorRef' is missing in type 'HTMLElement'. 
(<MatCheckbox>document.getElementById('asdasd')).checked = true;

How can I solve this, or is there a better way to do something with an checkbox without using [(ngModel)]?

FAISAL
  • 33,618
  • 10
  • 97
  • 105
Leonzen
  • 1,195
  • 5
  • 13
  • 30

3 Answers3

12

Use ViewChild decorator. Change your template to this:

<mat-checkbox class="toolbar-checkbox" #myCheckbox>
    MyCheckbox
</mat-checkbox>

.. and in your typescript:

import { ViewChild } from '@angular/core';
import { MatCheckbox } from '@angular/material';

@Component({
    ..... 
})
export class YourComponent {
    @ViewChild('myCheckbox') private myCheckbox: MatCheckbox;

    // You can then access properties of myCheckbox 
    // e.g. this.myCheckbox.checked
}

See this working StackBlitz demo.

FAISAL
  • 33,618
  • 10
  • 97
  • 105
0

You can also do:

<mat-checkbox class="toolbar-checkbox" [checked] = "myCondition" id="myCheckbox">
    MyCheckbox
</mat-checkbox>

where myCondition is set in the template or the class and could be any logical expression.

or

<mat-checkbox class="toolbar-checkbox" id="myCheckbox" [checked] = "myCondition()">
    MyCheckbox
</mat-checkbox>

where myCondition() is a method defined in the class and should return a boolean value, based on any logical expression.

This would allow you skip any DOM manipulation and take care of the checkbox checked status in the template.

Vega
  • 27,856
  • 27
  • 95
  • 103
  • 1
    Not a good solution. This will cause a neverending call of the function, causing slowness and bad performance. (Try console logging something inside the function and you'll see). – letie Feb 18 '20 at 18:55
0

Digging through what mat-checkbox generate in html i found that mat-checkbox create a hidden html input type="checkbox" so you can get the checked value by adding "-input" in the id in the getElementById call, for example if your mat-checkbox id is myinputid:

const getmyinput: boolean = (<HTMLInputElement>document.getElementById('myinputid-input')).checked;

It solve the problem for dynamic id, example adding string i in the middle:

const getmyinput: boolean = (<HTMLInputElement>document.getElementById('myinputid' + String(i) + '-input')).checked;