我想在ngAfterContentInit()中触发点击事件。
运行下面的代码,我得到了错误:
ERROR TypeError: Cannot read property 'click' of null
由于我使用NgFor来打印出所有的mat-复选框,
恐怕我无法使用ViewChild方法来实现我的目的。
组件:
<div *ngFor="let item of NationlityList.NationlityList; let i = index">
<div *ngIf="i % 6 == 0" class="row">
<mat-checkbox id="{{'Id'+i}}" *ngIf="i + 0 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i].Nationality)"> {{ NationlityList.NationlityList[i].Nationality }} </mat-checkbox>
<mat-checkbox id="{{'Id'+(i+1)}}" *ngIf="i + 1 < NationlityList.NationlityList.length" (change)="onCheckboxChecked($event, NationlityList.NationlityList[i+1].Nationality)"> {{ NationlityList.NationlityList[i+1].Nationality }} </mat-checkbox>
</div>
</div>
TS:
ngAfterContentInit() {
if (this.passedData.SelectedNationlity[0] !== 'All') {
let element: HTMLElement = document.getElementById('Id21');
element.click();
}
}
答案 0 :(得分:1)
您可以这样做:
document.getElementById('checkboxID').setAttribute('checked','true')