Error: Unable to access the 'nativeElement' property because it is undefined - occurring during the ngAfterViewChecked lifecycle hook

I am facing issues with some of my karma jasmine unit tests failing after adding an ngAfterViewChecked. Despite initializing the "mySwitchEl" as shown below, the error persists.

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

}

Below is a snippet of the unit test code. Placing "fixture.detectChanges" in the beforeEach causes all unit tests to fail instead of just 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();
   }
}

Here's a sample of the HTML structure:

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

Any insights on what could be causing these errors?

Answer №1

After some consideration, I found it necessary to include a conditional statement within the ngAfterViewChecked() function.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for managing your time while anticipating an observable that may or may not

I am facing a dilemma in my Angular app where I need to conditionally make an HTTP call to check for the existence of a user. Depending on the result of this call, I may need to either proceed with another API request or halt the processing altogether. I ...

Angular Universal functioning fine on local host, yet encountering issues on Nginx Server

I recently developed a project with Angular Universal. After building the project, it generated files such as browser, server, server.js, and prerender.js. I am curious to learn how I can run this project on an nginx server. Currently, I create a build o ...

Using Vivus.js in an Angular 5 Component

I am currently facing some challenges while attempting to incorporate Vivus.js library into Angular 5. The issue seems to be arising from the constructor of Vivus, which suggests that the library is being loaded correctly but not recognizing my element id. ...

Exploring the magic of Angular 4's FormBuilder: creating dynamic FormControls within a

My application enables users to choose from a dropdown menu of events, each with its own unique properties and selectable property values. This is achieved by creating a FormGroup for each event, with a FormControl for each property. Upon initialization, ...

I'm on the lookout for a component similar to angular-ui-tree that is compatible with angular

As a new developer, I am in search of a component similar to: But specifically for Angular 6, with all the same functionality (drag-and-drop capability, nested items, JSON structure, etc.). I have come across some components that either lack dragging fun ...

ASP.Net Core 3.1 server receives a blank user in JWT Bearer token

Today, I've been working on integrating JSON Web Token information with HttpContext.User using the Microsoft.AspNetCore.Authentication.JwtBearer library. The Issue: Whenever I make a request to the server, I can access functions with the [Authorize] ...

Angular 4 - Custom global error handler fails to capture Http errors

I have implemented a global event handler in my Angular application: import { ErrorHandler, Injectable, Injector } from '@angular/core'; import { Router } from '@angular/router'; @Injectable() export class GlobalErrorHandler implements ...

The "pointer" cursor style is simply not functioning in any way

Here is the angular template code I am working with: <!-- Modal --> <ng-template #levelsmodal let-c="close" let-d="dismiss"> <div class="modal-header"> Select the levels you want to show in the table and chart ...

Arranging an array in Angular 7 with various states and numbers

Looking to tackle this array sorting issue in Angular 7, the data is fetched from the API: "Products": [ { "ProductCode": "MC30180", "Description": "Description_1", "NationalCode": "N.C. 0965", "Pend ...

Guide on how to upload files to a web server using Angular frontend only

My website's frontend is built with Angular and it allows users to upload files. I am looking for a way to store these uploaded files on the web server where my website is currently hosted. Ideally, I would like to accomplish this using just Angular, ...

Experimenting with an Angular 2 component using a simulated service

Currently, I am experimenting with testing an Angular2 component that relies on a service. In order to conduct the test effectively, I aim to provide a stubbed service. However, it appears that the test component does not recognize this stubbed service. ...

Encountering an issue with the factory test within the controller, as it indicates that

Seeking assistance with testing the function below within a controller. getEmployeeList is a function within the controller that loads data in the UI upon controller initialization. It relies on a factory, but after implementing the code snippet below in ...

Highcharts - Customize Pie Chart Colors for Every Slice

I'm working on an angular app that includes highcharts. Specifically, I am dealing with a pie chart where each slice needs to be colored based on a predefined list of colors. The challenge is that the pie chart is limited to 10 slices, and I need to a ...

How do I use [(ngModel)] to set custom multiple select with 'selected' options with Angular and Materialize CSS?

Below is a snippet of code I am working with: <div class="input-field col s12"> <select name="uniqueName" [(ngModel)]="model.servicesIds" multiple> <ng-container *ngFor="let service o ...

Error encountered following the upgrade of Angular and RxJS 5 to 6: Compilation failed

Since updating my libraries to the latest Angular 6 and RxJS 6, I've encountered an issue. I have a RouteService class that functions as a service. It utilizes the HttpClient to fetch data from a remote API. However, after the update, I'm facing ...

Determining the total number of items in an array in Angular efficiently without causing any lag

Currently, I am using the function checkDevice(obj) to validate if a value is present or not. In addition to this functionality, I also require a separate method to determine the number of occurrences of Device in the Array. component.ts public checkDevi ...

Error message: "Using AngularFire 2 caused an issue as Firebase is not identified as a

I am interested in creating a sample app using Ionic 2 and AngularFire 2. After successfully integrating AngularFire 2 into Ionic 2, I encountered an error while trying to retrieve data from Firebase. The error message displayed in the browser console: ` ...

Experiencing issues with Errors when Targeting ES5 in Angular2 TypeScript?

In my development environment, the npm version is 3.10.10, and I want to create a new Angular2 project from scratch. When I try running npm install angular2 --save I encounter this error message: Error Image After referring to this answer which recomm ...

Incorrect object being returned from Angular 2 HTTP request

For my data fetching from the server, I am using @angular/http get method. Below is the code snippet: private _currentPT: any; public phongtroDetailChange = new Subject(); layPhongtro(id: number): Promise<any> { return new Promise((resolve, reject) ...

Tips for sending information to a nested Angular 2 attribute component

As per the instructions found on this blog, in order to create inner components within an SVG using Angular 2, we need to utilize an [attribute] selector: // Within svgmap.component.ts file: component declaration @Component({ selector: '[svgmap]& ...