【问题标题】:TypeError: Cannot read property 'nativeElement' of undefined -- in ngAfterViewCheckedTypeError:无法读取未定义的属性“nativeElement”——在 ngAfterViewChecked
【发布时间】:2019-12-13 14:39:52
【问题描述】:

添加 ngAfterViewChecked 后,我的一些 karma jasmine 单元测试失败。我不确定我在这里做错了什么。我尝试初始化下面的“mySwitchEl”,但仍然出现同样的错误。

@Component({
    selector: 'my-component',
    templateUrl: './my.component.html'
})

export class MyComponent implements OnInit, OnDestroy, AfterViewChecked {

   @ViewChild('myswitch') mySwitchEl: ElementRef;

   public somethingEnabled: boolean;

   public switchWidth: number;

   constructor(private cd: ChangeDetectorRef) { 
   }

   ngOnInit(): void { 
      // do stuff 
   }

   ngOnDestory(): void {
      // do stuff 
   }

   ngAfterViewChecked(): void {
      this.switchWidth = this.mySwitchEl.nativeElement.offsetWidth * 2;
      this.cd.detectChanges();
   }

}

这里是单元测试。如果我将“fixture.detectChanges”放在 beforeEach 中,我的所有单元测试都会失败,而不仅仅是少数。

    import { Component, ViewChild, ElementRef, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('myswitch') mySwitchEl: ElementRef;

   public somethingEnabled: boolean;

   public switchWidth: number;

   constructor(private cd: ChangeDetectorRef) { 
   }

   ngOnInit(): void { 
      // do stuff 
   }

   ngOnDestory(): void {
      // do stuff 
   }

   ngAfterViewChecked(): void {
      this.switchWidth = this.mySwitchEl.nativeElement.offsetWidth * 2;
      this.cd.detectChanges();
   }
}

html 示例

<label class="switch-light" [style.width.px]="switchWidth">
   <a class="btn btn-primary" id="my-switch-identifier" #myswitch>
      Some Text Here
   </a>
</label>

我在这里做错了什么?

【问题讨论】:

  • 这段代码无法编译,this.alertsSwitchElngAfterViewChecked 内部被访问,但它没有在任何地方定义。
  • @uminder - 抱歉,我在发布时更改了变量名。 this.alertsSwitchEl 应该是“mySwitchEl”。更新了我的帖子
  • 上面的代码工作正常。其他地方可能有问题。创建一个堆栈闪电战。
  • @MaihanNijat - 代码有效,但单元测试对我来说失败了。单元测试对你有用吗?

标签: angular angular7 karma-jasmine


【解决方案1】:

我必须在 ngAfterViewChecked() 中添加一个条件语句

    ngAfterViewChecked(): void {
      if(this.mySwitchEl) {
         this.switchWidth = this.mySwitchEl.nativeElement.offsetWidth * 2;
         this.cd.detectChanges();
      }
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2017-12-15
    • 2017-09-28
    • 1970-01-01
    • 2021-01-02
    • 2019-03-17
    相关资源
    最近更新 更多