【问题标题】:Angular mat-checkbox getElementById角垫复选框getElementById
【发布时间】:2018-03-31 15:31:10
【问题描述】:

我在使用 angular material 的 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)]?

【问题讨论】:

    标签: angular angular-material angular-material2


    【解决方案1】:

    你也可以这样做:

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

    【讨论】:

    • 不是一个好的解决方案。这将导致函数的无休止调用,从而导致速度缓慢和性能下降。 (尝试控制台在函数内记录一些东西,你会看到)。
    【解决方案2】:

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

    【讨论】:

    • 如果我的复选框有动态 id 怎么办?
    • @LetieTechera 你能分享一下你的组件看起来如何的 stackblitz 示例吗?
    猜你喜欢
    • 1970-01-01
    • 2018-05-03
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 2018-08-21
    • 2021-02-09
    相关资源
    最近更新 更多