Search code examples
angularangular7karma-jasmine

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


Some of my karma jasmine unit tests are failing after I added an ngAfterViewChecked. I am not sure what I am doing wrong here. I tried initializing the below "mySwitchEl" but still got the same error.

@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();
   }

}

Here is the unit test. If I put "fixture.detectChanges" in the beforeEach, all of my unit tests fail instead of only a few.

    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();
   }
}

Sample of the html

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

What am I doing wrong here?


Solution

  • I had to add a conditional statement to ngAfterViewChecked()

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