Are there any significant changes in Angular when transitioning from Angular 8 to 9 with regards to the nativeElement?

After upgrading my angular cli version to 9.1.4 from the previous version 8, I am wondering if there are any breaking changes related to nativeElement functionality.

Below is a snippet of code from my TypeScript file where I have used nativeElement:

import { Component, OnInit, ViewChild, ElementRef, Renderer2, Input } from '@angular/core';

@Component({
  selector: 'app-note-card',
  templateUrl: './note-card.component.html',
  styleUrls: ['./note-card.component.scss']
})
export class NoteCardComponent implements OnInit {

  @Input() title: string;
  @Input() body: string;

  @ViewChild('truncator') truncator: ElementRef<HTMLElement>;
  @ViewChild('bodyText') bodyText:ElementRef<HTMLElement>;

  constructor(private renderer: Renderer2) { }



ngOnInit() {

    // Determine text overflow and show/hide truncator accordingly

    let style = window.getComputedStyle(this.bodyText.nativeElement, null);
    let viewableHeight = parseInt(style.getPropertyValue("height"), 10);

    if(this.bodyText.nativeElement.scrollHeight>viewableHeight){
      this.renderer.setStyle(this.truncator.nativeElement, 'display', 'block');
    }else{
      this.renderer.setStyle(this.truncator.nativeElement, 'display', 'none');
    }
  }

}

I am encountering the following error in the browser:

ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at NoteCardComponent.ngOnInit (note-card.component.ts:22)
    at callHook (core.js:4735)
    at callHooks (core.js:4699)
    at executeInitAndCheckHooks (core.js:4639)
    at selectIndexInternal (core.js:9701)
    at Module.ɵɵadvance (core.js:9662)
    at NotesListComponent_Template (notes-list.component.html:19)
    at executeTemplate (core.js:12098)
    at refreshView (core.js:11945)
    at refreshComponent (core.js:13410)
defaultErrorLogger @ core.js:6237

If anyone could provide assistance, it would be greatly appreciated. Thank you in advance :)

Answer №1

When utilizing the ViewChild decorator within the OnInit lifecycle hook, it is crucial to specify the static property as true in order to resolve query results prior to change detection taking place. By default, this property is set to false, resulting in resolution after change detection occurs.

If you are implementing this in ngOnInit, such as in your specific scenario, refer to the code snippet provided below:

  @ViewChild('truncator', { static: true }) truncator: ElementRef<HTMLElement>;
  @ViewChild('bodyText', { static: true }) bodyText:ElementRef<HTMLElement>;

In cases where you are not using it within OnInit, remember to set the property to false. It is worth noting that in Angular 9, this step is optional since the default value is false in such instances.

I am curious as to how you managed to avoid errors in Angular 8, considering that this property was mandatory for both scenarios back then.

Answer №2

@ViewChild() decorator allows access to selected elements starting from AfterViewInit onwards. Therefore, it is recommended to transfer your code execution from the ngOnInit method to the ngAfterViewInit method.

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

What makes components declared with "customElements.define()" limited in their global usability?

I've been tackling a project in Svelte, but it involves some web components. The current hurdle I'm facing is with web components defined using the customElements.define() function in Typescript, as they are not accessible unless specifically im ...

Using React with Axios to trigger several requests with a single action

Let's say a user selects a team from a dropdown menu, triggering a request to an API endpoint. const selectHomeTeamStat = evt => { const { value } = evt.target; getStats(leagueId, value, 'home'); }; In this hypothetical scen ...

What is the best way to conceal a button before printing and have it reappear once the printing process is finished?

I have a button on my webpage with the id "print_req" that is used to trigger a JavaScript function for printing the page. I want this button to be hidden during the printing process and then reappear afterwards, so it does not show up in the printed docum ...

The TypeScript declaration for `gapi.client.storage` is being overlooked

When I call gapi.client.storage.buckets.list(), TypeScript gives me an error saying "Property 'storage' does not exist on type 'typeof client'." This issue is occurring within a Vue.js application where I am utilizing the GAPI library. ...

Experiencing a No data error when attempting to confirm Authentication using passkey with SimpleWebAuthn in conjunction with Node.js and react.js

I am currently implementing passkey login functionality in my react.js app with a node.js backend and MongoDB database. Below is the code snippet for the backend: const registerWebAuthentication = async (req, res) => { // Backend code for registering ...

How to utilize a Multidimensional JSON Array in a jQuery Function

I'm struggling with passing a PHP array to a jQuery function and accessing values from a multidimensional JSON array. When I try to retrieve the value of 'lat' using the code below, I receive an error stating Cannot read property 'lat&a ...

Preventing v-stepper-step header click in Vuetify.js when form is invalid

I'm using Vuetify's v-stepper component. What I'm trying to achieve is: When a user clicks on a stepper step in the header, I want to block the click event if the active form is not valid. I have been able to accomplish this by attaching ...

Is there a way to enhance the readability of intellisense output for Typescript generics using the Omit method?

Scenario: I have customized a third-party library for users by removing two properties from all functions in the library. I have implemented a function to achieve this, along with executing a bootstrap function if provided. Here is the code snippet: const ...

I'm experiencing difficulty uploading videos and audios using Google Gemini API version 1.5Pro

Looking for assistance in utilizing the Google Gemini API 1.5Pro model for Video/audio Processing. I've exhaustively searched through various search engines, but haven't been able to find any resources on how to do this. My goal is to upload an ...

Is it necessary to use JS/JQ to trigger PHP form data?

Can PHP files/functions be executed without reloading the page? It can be quite disruptive when developing a chat app and every time you send a message, the entire page refreshes. I attempted to use AJAX but it didn't work. Is it not possible to send ...

Retrieve data from an array within the user Collection using Meteor and React Native

I need assistance with retrieving the entire array [votes] stored within the User Collection. Below is the JSON structure { "_id" : "pziqjwGCd2QnNWJjX", "createdAt" : ISODate("2017-12-21T22:06:41.930Z"), "emails" : [ { "a ...

Is there a way to update the dictionary in the context processor without having to reload the page?

I have implemented a custom context processor that returns the value of "unread_messages_count". However, when I try to update this value on the template using the following JavaScript: var update_message_count = setInterval(function(){ ...

How to Verify Username in Angular2 and Sails Framework

Currently, I am implementing Angular2 on the front end and Sails.js on the back end. When a user registers, it is necessary to validate whether the chosen username already exists in the database. The backend system developed using Sails will respond with J ...

Is there a way to divide all the characters within a string, excluding the sequence " "?

My issue (resolved) I've been working on an animation where each letter appears sequentially, but I encountered a problem. In order to transform the letters properly, I had to wrap my span tags in a flex div because using inline-block didn't all ...

Assigning string properties to different types

I have numerous data types, each with a common property called dataType, and I am currently mapping each one to that specific value: interface GroupData { dataType: "group"; name: string; people: PersonData[]; } interface PersonData ...

Identify when two calendar dates have been modified

Creating a financial report requires the user to select two dates, search_date1 and search_date2, in order for a monthly report to be generated. Initially, I developed a daily report with only one calendar, where I successfully implemented an AJAX script ...

The appearance of the image varies between Chrome and Internet Explorer

Greetings fellow web developers! Currently, I am facing an issue with a logo embedded in a navigation bar displaying differently in Chrome compared to IE version 10 running document standards. The webpage is utilizing bootstrap CSS. Here is the code snippe ...

Displaying the chosen option from the V-menu in a different section of the application. Utilizing Vuetify

I'm working with a v-menu that has multiple options. I want to be able to display the selected option in another section of my application within the same component. Even though I attempted to use v-model for this purpose, it doesn't seem to work ...

Issue encountered: NullInjectorError - R3InjectorError has been caused by a problem within AppModule regarding InjectionToken HTTP_INTERCEPTORS linking to TransferState

Error Image:- Error Images I am encountering this error: ERROR NullInjectorError: R3InjectorError(AppModule)[InjectionToken HTTP_INTERCEPTORS -> [object Object] -> TransferState -> TransferState -> TransferState]: NullInjectorError: No provider ...

Is It Best to Override Behavior in a Directive?

Having two directives that display lists of documents, one for user-favorited documents and the other for user-pinned documents. The criteria for displaying these documents depend on the values of "pinned" and "favorite" within each document object: docum ...