What steps should I take to fix the error "property scrollIntoView of null cannot be read"?

I start a new project using Angular

.html file:

<a (click)="go()">toto</a>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam iaculis ex 
porttitor semper iaculis. Nam dapibus erat interdum, scelerisque magna et, finibus sapien. Aliquam tempus porta ante id rhoncus. Cras sit amet consequat tellus, at malesuada tellus. Vivamus et augue dolor. In consequat pretium massa in imperdiet. Donec sapien nulla, commodo sed est et, lacinia sodales augue. Curabitur sed neque vel quam consequat blandit. Curabitur rutrum commodo pretium. Maecenas posuere, nibh a ultricies laoreet, orci...

Nullam pretium tellus odio. Donec hendrerit odio vel pellentesque imperdiet. Integer eget auctor magna, ut placerat tortor. Donec ut ante fermentum, molestie augue fringilla, ornare nunc.</div>
<div [hidden]="!show">
    <h2 id="step1">titi</h2>
</div>

.ts file:

show : boolean = false
go(){
    this.show = true
    document.getElementById("step1").scrollIntoView({behavior : "smooth"})
}

However, I encounter an error when clicking on the anchor tag for the first time :

Cannot read property scrollIntoView of null

What steps should be taken to resolve this issue?

Answer №1

Replace your *ngIf directive with the hidden attribute in the following manner:

HTML:

<div>Some elements</div>
 <a (click)="go()">toto</a>
<div [hidden]="!show">
  <h2 #step1>titi</h2>
</div>

TS:

@ViewChild('step1') step1: ElementRef;
  show : boolean = false
go(){
    this.show = true;
    this.step1.nativeElement.scrollIntoView({ behavior: "smooth"});
}

The rationale behind this change is that initially Angular may not find an element with the id 'step1' because when using *ngIf, the element is removed from the DOM. On the other hand, using hidden simply hides the element without removing it from the DOM.

See a Demo Here

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

Updating the appearance of a non-declared HTML child component on-the-fly using Angular

Trying to dynamically adjust the style of an unspecified div is causing some trouble. Using Angular and PrimeNG, invisible divs are being generated that I cannot access through inline styles. The objective is to allow a user to input a width as a string (5 ...

Creating an array of Form Groups involves first initializing an empty array and then

Here is a JSON object that I need to create a reactive form based on. What steps should I take for the array portion specifically? { "examName" : "java", "password" : "1234.com", "examCategory" : { "id" : 78 }, "examDetailSet" ...

Issue encountered on IIS 7.x server during deployment with HTTPS

Currently, I am running an Angular + .Net 4.5 fullStack application on IIS V7.5 with Windows Server. To conduct additional tests, I am using multiple instances of the same site with different versions of the application deployed on the same host. Each inst ...

The URL is reverted back to the previous address

Currently in the process of developing an Angular application, I've encountered a minor visual issue. On one of the pages, there is a ReactiveForm implemented, but whenever I navigate to that page, the URL reverts back to the previous one (even though ...

What is the best way to handle installing peer dependencies when using Angular CLI?

Every time I try to update my Angular CLI and NPM, I get stuck in a cycle of errors. After updating, I receive WARN messages instructing me to install peer dependencies (listed below). However, when I try to install these dependencies, more WARN messages a ...

Issues arising from TypeScript error regarding the absence of a property on an object

Having a STEPS_CONFIG object that contains various steps with different properties, including defaultValues, I encountered an issue while trying to access the defaultValues property from the currentStep object in TypeScript. The error message indicated tha ...

Exploring the usage of intervalTimer with async and fakeAsync functions

In a particular section of the Angular Testing Guide, it discusses how to test components with asynchronous services, pointing out that: When writing test functions involving done rather than async and fakeAsync, it may be more cumbersome but remains a ...

Issue with unit testing a ViewportRuler in Angular 2 Material Library

I am currently working on an Angular2 component that includes a tab control from @angular/material. During testing of my component (refer to the simplified code below), I encountered the following error: Error: Error in ./MdTabHeader class MdTabHeader - ...

Getting permission for geoLocation service on iOS in Ionic: A step-by-step guide

I have recently developed a social media application that utilizes geoLocation services. The app is built with Ionic 4 and has a Firebase backend. While the GeoLocation services are functioning properly on Android devices, users of iOS are not being prompt ...

Angular enables the use of multiple instances of a service from the parent component to the child component

I recently came across this discussion: Utilizing multiple instances of the same service. Can one utilize multiple instances of a service from parent to children? For instance, imagine having an ElementService in the ParentComponent with 2 separate instan ...

The Angular application is not functioning properly after running npm start, even though all the necessary packages have

Encountering a perplexing issue with my Angular application. After checking out the code on my new machine, I attempted to run my existing Angular 12 project. However, despite the application running properly in the command prompt, it is not functioning as ...

Enhance your coding experience with code completion and autocomplete in Angular/Typescript using ATOM within

Is it possible to have Codecompletion / Autocomplete in Atom similar to Webstorm? Currently I am getting familiar with TypeScript and really enjoying it, but the lack of Codecompletion support for my HTML files in Atom is quite frustrating. Having this f ...

Issue with default country placeholder in Ionic 6.20.1 when using ion-intl-tel-input

I have successfully downloaded and set up the "ion-intl-tel-input" plugin from https://github.com/azzamasghar1/ion-intl-tel-input, and it is functioning properly. However, I am facing an issue with changing the default country select box placeholder from " ...

Angular 2: Applying a class to a specific element by referencing its id

I am trying to figure out how to add a class to an element with a specific id in Angular 2. In regular JavaScript, you can do it like this, but I need help translating this into Angular 2: document.getElementById("MyElement").className += " active"; Cur ...

IdentityServer4: The authentication time is not specified

I'm currently working on an angular (asp.net core) application that utilizes an identityserver4 server for authentication. Initially, the login process works seamlessly, displaying the login form and returning both the id_token and access_token. How ...

Is it possible to remove a complete row in Angular 2 using Material Design

JSON [ { position: 1, name: 'test', value: 1.0079, symbol: 'HHH' }, { position: 2, name: 'test2', value: 4.0026, symbol: 'BBB' }, { position: 3, name: 'test3', value: 6.941, symbol: 'BB' }, ...

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...

How can elements be displayed differently depending on the return value of a function?

Basically, I am looking to display different content based on the status of a job: Show 'Something1' when the job is not processing Show 'Something2' when the job is running and has a status of '0' Show 'Something3&apos ...

Incorporating CodeMirror into Angular2 using TypeScript

I've been working on integrating a CodeMirror editor into an Angular2 project, but I'm encountering some issues with the instantiation of the editor. Here is my code snippet: editor.component.ts import {Component} from 'angular2/core' ...

What in the world is going on with this Typescript Mapped type without a right-hand side?

I encountered a situation where my React component had numerous methods for toggling boolean state properties. Since these functions all did the same thing, I wanted to streamline the process by creating a common function for toggling properties. Each met ...