2017-10-19 99 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操作並處理模板中的複選框選中狀態。