【问题标题】:DOM undefined when the element is inside a *ngIf container当元素在 *ngIf 容器内时,DOM 未定义
【发布时间】: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 回答的那样,@ViewChildstatic: true 装饰器使您的元素只能在ngOnInit 执行前在组件范围内访问,因此,不要在构造函数中添加逻辑,而是尝试在初始化生命周期钩子组件中替换它。

标签: javascript angular typescript


【解决方案1】:

我可能不知道它背后的真正原因,但我认为 Angular 需要一点时间来首先渲染 ngIf 元素内的任何内容,然后再提供给 DOM。

您可以通过在此处将 static 更改为 false 来解决您的问题

@ViewChild('myTable', {static: false}) myTable: MatTable<any>;

并在 setTimeout

中调用 this.myFunctionIfNotHavePermissions()
constructor(){
  if(checkSomething == true){
      this.hasPermission = false
      setTimeout(()=> this.myFunctionIfNotHavePermsissions());
  }
}

【讨论】:

  • 我只把静态改成false,就可以了!!
【解决方案2】:

在构造函数中,您的模板尚未准备好并且未呈现 mat-table。

ngOnInit中添加你的逻辑

export class MyComponent implements OnInit {

   hasPermission = true

   @ViewChild('myTable',{static:true}) myTable: MatTable<any>;


   constructor() {}


   ngOnInit() {
      if(checkSomething == true){
          this.hasPermission = false
          this.myFunctionIfNotHavePermsissions()
      }
   }

   myFunctionIfNotHavePermsissions(){
      this.myTable.renderRows();
      // console.log(this.myTable); *NOTE: This output: undefined*
   }

}

【讨论】:

  • 我将逻辑移动到 ngOnInit 并且问题继续存在,但是如果我将静态更改为 false,似乎没有必要将逻辑移动到 ngOnInit
猜你喜欢
  • 2015-01-05
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 2015-04-27
  • 1970-01-01
相关资源
最近更新 更多