2017-10-19 97 views
2

我从角度材质的mat-checkbox出现问题。我已经给该复选框的ID是这样的:角度mat-checkbox getElementById

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

之后,我想的东西与此元素是这样的:

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

但unfortunally我得到这个错误:

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

我该如何解决这个问题,或者是否有更好的方法来使用复选框而不使用[(ngModel)]?

回答

4

使用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 demo

+1

主席先生,让我高兴 - 你打败了我! – rinukkusu

+1

Danke Schon @rinukkusu \ o / – Faisal

0

你也可以这样做:

<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操作并处理模板中的复选框选中状态。