首页 文章

Angular mat-checkbox getElementById

提问于
浏览
2

我有角度材料的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)]?

2 回答

  • 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 .

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

相关问题