[英]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.