【发布时间】:2020-12-01 17:11:01
【问题描述】:
我的问题是当元素是 *ngIf 容器的子元素时,我无法访问特定的 DOM 元素及其属性。
我的情况是:我在 div 中有一个 mat-table,该 div 有 *ngIf 指令,然后当我的数据源更改时我尝试调用 mytable.renderRows(),但我得到了一个未定义的值。我看到当元素在 ngIf 指令内时会发生此问题,在其他情况下我可以毫无问题地访问。
<div *ngIf="!hasPermission" >
<table mat-table #myTable [dataSource]="myDataSource">
我在 .ts 文件中有这个:
export class MyComponent {
hasPermission = true
@ViewChild('myTable',{static:true}) myTable: MatTable<any>;
constructor(){
if(checkSomething == true){
this.hasPermission = false
this.myFunctionIfNotHavePermsissions()
}
}
myFunctionIfNotHavePermsissions(){
this.myTable.renderRows();
// console.log(this.myTable); *NOTE: This output: undefined*
}
}
目前,我解决了这个问题,使用 css 隐藏了 div,但我认为这不是最好的解决方案,提前感谢您的 cmets。
<div *ngIf="!hasPermission" >
to
<div [ngClass]="{ 'nodisplay': !hasPermission}" >
.nodisplay{display:none!important;}
【问题讨论】:
-
正如@miladfm 回答的那样,
@ViewChild的static: true装饰器使您的元素只能在ngOnInit执行前在组件范围内访问,因此,不要在构造函数中添加逻辑,而是尝试在初始化生命周期钩子组件中替换它。
标签: javascript angular typescript