Angular 5 is throwing an error that says: "There is a TypeError and it cannot read the property 'nativeElement' because it

Being aware that I may not be the first to inquire about this issue, I find myself working on an Angular 5 application where I need to programmatically open an accordion.

Everything seems to function as expected in stackblitz, but unfortunately, I am encountering issues in my actual project.

I have meticulously checked all script references and their alignments across both projects but failed to identify any discrepancies.

For reference, here is the link to the stackblitz version:

https://stackblitz.com/edit/angular-bootstrap-carousel-dynamic2-zqoeiw?file=index.html

Error:

ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at eval (eval at ../../../../../src/app/Components/List And Grid View Components/common/common.component.ts (main.bundle.js:28), <anonymous>:56:20)
    at SafeSubscriber.schedulerFn [as _next] (core.js:4331)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:240)
    at SafeSubscriber.next (Subscriber.js:187)
    at Subscriber._next (Subscriber.js:128)
    at Subscriber.next (Subscriber.js:92)
    at EventEmitter.Subject.next (Subject.js:56)
    at EventEmitter.emit (core.js:4299)
    at QueryList.notifyOnChanges (core.js:6439)
    at checkAndUpdateQuery (core.js:12833)

app.componant.html

<div class="accordion col-sm-12" id="accordion1" *ngFor='let data of dropdownData; let i=index'>
    <div class="accordion-group">

        <div class="accordion-heading">
            <a class="accordion-toggle h6" data-toggle="collapse" routerLink="/two/{{i}}" data-parent="#accordion1" href="#collapseTwo + i">
                {{data?.CAMD_ENTITY_DESC}}
            </a>
        </div>
    </div>
</div>

app.module.ts

const appRoutes: Routes = [
      {path:'one',component:OneComponent},
       {path:'two/:id',component:TwoComponent}]

common.component.html

<div class="accordion col-sm-12" id="accordion1" *ngFor='let data of dropdownData; let i=index'>
        <div class="accordion-group">

          <div class="accordion-heading">
            <a class="accordion-toggle h6" data-toggle="collapse"    data-parent="#accordion1" href="#collapseTwo + i" #accordian>
              {{data?.CAMD_ENTITY_DESC}}
            </a>
          </div>
//other codes
</div>
</div>

common.component.ts

import { Component, OnInit, ViewChildren, QueryList, AfterViewInit, ElementRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';
import { CartdataService } from '../../../services/cartdata.service';

declare var $: any;

@Component({
  selector: 'app-common',
  templateUrl: './common.component.html',
  styleUrls: ['./common.component.css']
})

export class CommonComponent implements OnInit, AfterViewInit {

  id: string;
  dropdownData: any;

  @ViewChildren('accordian') components: QueryList<ElementRef>;
  constructor(private route: ActivatedRoute, private router: Router, private CartdataService: CartdataService) { }

  ngOnInit() {

    this.CartdataService.get_Product_Categories().subscribe(
      data => {
        this.dropdownData = data;
      });
    this.id = this.route.snapshot.paramMap.get('id');
  }


  ngAfterViewInit() {
    this.components.changes.subscribe(() => {
      let elem = this.components.toArray()[this.id];
      $(elem.nativeElement).trigger("click");
    });
  }
}

index.html

<body>

  <app-root></app-root>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
    crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
    crossorigin="anonymous"></script>


</body>

angular-cli.json

"styles": [
        "styles.css"
      ],
      "scripts": [
        "../node_modules/jquery/dist/jquery.min.js",
    "../node_modules/bootstrap/dist/js/bootstrap.min.js"
      ]

package.json

"dependencies": {
    "@agm/core": "^1.0.0-beta.2",
    "@angular/animations": "^5.2.0",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.0",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "angular-web-storage": "^2.0.0",
    "angular-webstorage-service": "^1.0.2",
    "auth0-js": "^9.3.1",
    "bootstrap": "^4.1.1",
    "core-js": "^2.4.1",
    "dateformat": "^3.0.3",
    "jquery": "^3.3.1",
    "jquery.js": "0.0.2-security",
    "popper.js": "^1.14.3",
    "public-ip": "^2.4.0",
    "rxjs": "^5.5.6",
    "zone.js": "^0.8.19"
  }

If anyone could assist me in identifying any mistakes I have made and provide guidance on resolving these errors, it would be greatly appreciated.

Answer №1

The reason for this issue is the absence of any element that can be discovered by @ViewChildren('accordian'). None of the elements in the view are referenced as accordian. To add a reference, follow this format:

<div #reference></div>

In your scenario,

<div #accordian></div>

MODIFY

The problem lies within your business logic.

let elem = this.components.toArray()[this.id];

This is where you encounter undefined. Try executing

console.log(this.components.toArray())

to investigate what is being queried. Review and adjust your logic. All Angular-related aspects are functioning correctly 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

The div is incorrect and causing the label and input to move in the wrong direction

Whenever I try to adjust the position of the current-grade-name-input, the entire grade-point-input moves along with it inexplicably. /* final grade calculator: (wanted-grade - (current-grade * (1 - final%))) / final% Ex: have a 80 an ...

Techniques for a versatile class limited to a particular category

In my code, I have a Vector class that looks like this: class Vector<N extends number> {...} N represents the size or dimension of the vector. This Vector class also includes a cross product method to calculate the cross product between vectors: cro ...

What is the process for choosing and implementing action on an HTML element using Angular?

I have a block of HTML code like the one below, and I'm looking to implement an onclick event for the button element. <div> .... <button class="test"></button> .... </div> The button is dynamically generated usi ...

Guide to hosting AngularJS Material documentation on a local server

After gathering the latest angularjs material, I noticed that the links in the document lead to absolute URLs at material.angularjs.org/.... I wish to have access to read the documentation and demonstration content locally. ...

Show or conceal a child component within a React application

In my React render function, I am working with the following code: <div> <InnerBox> <div>Box 1</div> <HiddenBox /> </InnerBox> <InnerBox> <div>Box 2</div> & ...

Can you explain the distinction between interfaces containing function properties written as "f()" and "f: () =>"?

Let's take a look at two interfaces, A and B: interface A {f(): number} interface B {f: () => number} I have experimented with the following: var a: A = {f: function() {return 1}} var a: A = {f: () => 1} var b: B = {f: function() {return 1}} ...

Is there a way to instantiate a new object within the same for loop without replacing the ones created in previous iterations?

My current issue with this exercise is that as I convert the first nested array into an object, the iteration continues to the next nested array and ends up overwriting the object I just created. I'm wondering how I can instruct my code to stop itera ...

Encountering an error where property 'onClicked' is not defined when attempting to utilize chrome.action or chrome.browserAction in Chrome

I am currently developing a Chrome extension that will automatically redirect me to a specific URL when I click on the browser action icon. Here is the code snippet that I am trying to implement: chrome.browserAction.onClicked.addListener However, I am ...

Loading Disqus comments dynamically upon clicking a button within a Next.js application

After noticing a significant decrease in page performance scores due to Disqus comments embedded on Vercel Analytics, I am considering implementing a "Load comments" button instead of loading the actual comments onClick. I have been using the disqus-react ...

Utilizing Express, Request, and Node.js to manage GET requests in typescript

I'm struggling with using Express and Request in my project. Despite my efforts, the response body always returns as "undefined" when I try to get JSON data from the server. In my server.js file, this is the code snippet I have been working on: impo ...

Processing of an array received via AJAX and passed to a PHP script, inside a separate function in a different file

I have a JavaScript array that I am sending via AJAX to a PHP file named aux.php. What I want is for this array to be visible and manipulable within a function inside a class in another PHP file called payments.php. I've provided all the code so they ...

Is the Vue2 Template compiler malfunctioning?

When compiling my code using webpack(^5.51.1) and vue-loader(^17.0.0), I encountered an issue while trying to run an older project. The error message displayed is as follows: [webpack-cli] Failed to load '/var/www/webpack.config.js' config [webpa ...

What is the best way to access a particular property of an object?

Currently, I am successfully sending data to Mongo and storing user input information in the backend. In the console, an interceptor message confirms that the data is received from MongoDB. However, I am struggling to extract specific properties such as th ...

The kendo-angular-chart is missing the required dependency kendo-charts-1.19.1.tgz

Is anyone else experiencing issues with the kendo-chart installation? I am attempting to install kendo-angular-chart and encountering the following problem: npm install npm ERR! code E404 npm ERR! 404 Not Found - GET https://registry.npmjs.org/@progress/ ...

A step-by-step guide on fetching multiple iframe contents simultaneously with Selenium in Java

Today, I am facing an interesting challenge. I need to extract the page source of a webpage that includes an iframe. Surprisingly, when using the PhantomJSDriver with the code snippet below, I am only able to retrieve either the page content or the iframe ...

Incorporating XMLHttpRequest in my React Typescript App to trigger a Mailchimp API call, allowing users to easily sign up for the newsletter

My website needs to integrate Mailchimp's API in order for users to subscribe to a newsletter by entering their email into a field. I am looking to implement this without relying on any external libraries. To test out the functionality, I have set up ...

Guide to removing a Firebase Storage directory using a Firebase Cloud Function?

I'm having trouble finding the deleteFiles() method and the DeleteFilesOptions argument in the Firebase API reference. My IDE is indicating that this method requires an optional argument, but I can't seem to locate any information on this type. I ...

Issue with JQueryUI Dialog auto width not accounting for vertical scrollbar

My JQueryUI Dialog has the width property set to 'auto'. Everything functions properly except in situations where the content exceeds the height of the dialog: A vertical scrollbar appears, but it disrupts the layout of the content within the dia ...

Retrieve the mfData value from the TypeScript file in order to perform operations on it within the Angular 2 framework

I have a snippet of code that iterates through data from stacklist_table, which is a JSON array, and displays it in a table format. The stacklist_table contains a full list of objects, but I only need a subset of these objects so I have applied some filter ...

When compiling without the --aot flag, the matTable in Angular is causing an error stating "unable to read property 'find' of undefined."

An error is being thrown by the angular material table (matTable) when compiling without --aot. https://i.sstatic.net/i3qMF.png Although the application works fine when the target es version is set to es5, it heavily depends on es6 features. Therefore, i ...