角垫复选框getElementById [英] Angular mat-checkbox getElementById

查看:70
本文介绍了角垫复选框getElementById的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用角形材质的mat-checkbox遇到了问题.我给复选框提供了这样的ID:

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;

如何解决此问题,或者有没有使用[(ngModel)]复选框的更好方法?

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

推荐答案

使用 ViewChild > 装饰器.将模板更改为此:

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
}

查看此工作 StackBlitz演示 .

See this working StackBlitz demo.

这篇关于角垫复选框getElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆