TypeError:无法读取未定义的属性'nativeElement'-在ngAfterViewChecked中

时间:2019-12-13 14:39:52

标签: angular angular7 karma-jasmine

添加ngAfterViewChecked后,某些业力茉莉花单元测试失败。我不确定我在做什么错。我尝试初始化下面的“ 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();
   }

}

这是单元测试。如果我在beforeEach中放入“ fixture.detectChanges”,那么我所有的单元测试都会失败,而不是少数几个。

    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>

我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

我必须向ngAfterViewChecked()添加条件语句

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