TypeError: Cannot read property 'nativeElement' of undefined -- in ngAfterViewChecked

TypeError: Cannot read property 'nativeElement' of undefined -- in ngAfterViewChecked

我的一些 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();
   }

}

这是单元测试。如果我将 "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>

我做错了什么?

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

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