Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular mat-checkbox getElementById

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)]?

like image 212
Leonzen Avatar asked Oct 19 '17 14:10

Leonzen


People also ask

How to make mat checkbox checked by default in Angular?

To set mat-checkbox checked by default we use checked attribute or [ngModel] as shown below. We can set the IsChecked property to true in constructor.

How do you check mat checkbox is checked or not?

Angular Material <mat-checkbox> has a property checked that is used to check and uncheck the checkbox dynamically. At runtime we can check and uncheck checkbox by passing true and false value to checked property using property binding.

What is indeterminate in Mat checkbox?

<mat-checkbox> supports an indeterminate state, similar to the native <input type="checkbox"> . While the indeterminate property of the checkbox is true, it will render as indeterminate regardless of the checked value. Any interaction with the checkbox by a user (i.e., clicking) will remove the indeterminate state.

How do you check checkbox is checked or not in angular 8?

Just define an ng-model directive in the checkbox and to find checkbox checked or not check model return value (TRUE or FALSE). If it has TRUE means checkbox is been checked.


1 Answers

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.

like image 98
Faisal Avatar answered Sep 25 '22 02:09

Faisal