繁体   English   中英

Angular mat-checkbox getElementById

[英]Angular mat-checkbox getElementById

我对来自 angular 材料的 mat-checkbox 有疑问。 我给了复选框一个像这样的 ID:

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

之后,我尝试使用这样的元素:

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

但不幸的是我收到了这个错误:

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

我该如何解决这个问题,或者有没有更好的方法可以在不使用 [(ngModel)] 的情况下使用复选框来做某事?

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

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

..并在您的打字稿中:

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演示

您也可以:

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

其中myCondition是在模板或类中设置的,可以是任何逻辑表达式。

要么

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

其中myCondition()是在类中定义的方法,并且应基于任何逻辑表达式返回布尔值。

这将允许您跳过任何DOM操作,并注意模板中复选框已选中的状态。

通过挖掘 html 中生成的mat-checkbox ,我发现mat-checkbox创建了一个隐藏的 html input type="checkbox"因此您可以通过在getElementById调用的 id 中添加“-input”来获取选中的值,例如,如果您mat-checkbox id 是myinputid

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

它解决了动态 id的问题,例如在中间添加字符串i

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM