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

查看:28
本文介绍了角垫复选框 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天全站免登陆