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

Node.js encountering req.body as undefined when using form-data as the content-type

After creating a small demonstration for this form-data passing API, I attempted to test it using Postman. However, I encountered an issue where no data was being retrieved. Code const http = require("http"); const express = require("expres ...

KnockoutJS - Using containerless control flow binding with predefined values

Inside a select control, I am using ko:foreach instead of the usual bindings. Everything is working perfectly, except that the initial value for "specialProperty" is set to unknown even when the select control is set to Option 1. It behaves as expected o ...

What could be causing the issue of the title in req.body to display as 'undefined'?

I am currently learning about NODE JS and practicing working with POST forms from PUG to a NODE JS server. I am facing an issue where the submission input is coming back as 'undefined' when I submit a form from the web browser. In the code snipp ...

unable to press the electron button

I am currently working on a project that involves connecting PCs together for screencasting. While following an online coding tutorial, I encountered an issue with clicking the button to generate the ID code. Here is the code snippet from app.js: // Code ...

How does the question mark symbol (?) behave when utilizing it in response? Specifically in relation to data, the API, and the fetch API

Have you encountered the curious sequence of symbols in this context? data?.name Could you explain the significance of the question mark (?) between 'data' and the period? ...

Sending images as a base64 string from a Titanium app to a Ruby on Rails web service

I am encountering an issue when trying to upload an image from an app that has been converted into a base64 string to a Ruby on Rails server. The app is developed using Titanium. However, after retrieving and decoding the image string back into an image, ...

Unable to display Boostrap modal upon clicking href link

Can someone help me troubleshoot why my pop modal is not displaying after a user clicks on a specific link on my webpage? I have attempted the following: <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></s ...

Featuring a visual arrangement of categorized images with AngularJS for an interactive display

As I work on developing a web application with Angular, my goal is to create a grid layout that organizes items by category. Each row will represent a different category. Below is an example of the code structure I have in place: <ion-item ng-repeat="i ...

I encounter an error in my JavaScript function indicating that it is not defined

let element = document.querySelector("#value"); let buttons = document.querySelectorAll(".btn"); buttons.forEach(function (button) { button.addEventListener("click", function(event){ console.log(event.currentTarge ...

When utilizing the Express framework, the object req.body is initially empty when collecting data from a basic

I'm encountering an issue where I receive an empty object in req.body when submitting my HTML form. This problem persists whether testing in Postman or directly submitting the form from localhost in the browser. Upon logging it in the node console, t ...

Having trouble accessing the loadTokenizer function in Tensorflow JS

As a beginner with Tensorflow.js concepts, I recently attempted to tokenize a sentence using the Universal Sentence Encoder in Javascript. You can explore more about it on Github Reference $ npm install @tensorflow/tfjs @tensorflow-models/universal-sentenc ...

Incapable of modifying the text within a div container

I am currently working on a script that translates a Russian forum word by word using TreeWalker. However, there is a specific type of div element that I have been unable to change the text for. That leads to my question: How can I go about changing it? Un ...

Developing a versatile table component for integration

My frontend app heavily utilizes tables in its components, so I decided to create a generic component for tables. Initially, I defined a model for each cell within the table: export class MemberTable { public content: string; public type: string; // ...

What is the best way to show and hide text by toggling a link instead of a button?

I need help with toggling between two different texts when a link is clicked. I know how to achieve this with a button in JQuery, but I'm not sure how to do it with a link. <h1>Queries and Responses</h1> <p>Query: What is the larges ...

Ajax is functional, however the server is not responding

After many attempts to resolve the issue with my website, I am turning to this community in hopes of finding a solution. The problem lies in the fact that while the ajax success function appears to be working and shows a status code of 200 in the network ...

Learn the process of creating test cases using `ava` for the following code snippet

const TimeToEvent = minutes => { const oneMinute = 1; const minutesInAnHour = 60; if (minutes <= oneMinute) { return "in just 1 minute"; } if (minutes < minutesInOneHour) { return "in mere&quo ...

Having trouble launching the application in NX monorepo due to a reading error of undefined value (specifically trying to read 'projects')

In my NX monorepo, I had a project called grocery-shop that used nestjs as the backend API. Wanting to add a frontend, I introduced React to the project. However, after creating a new project within the monorepo using nx g @nrwl/react:app grocery-shop-weba ...

Embracing async-await while awaiting events in node.js

I am attempting to incorporate async await into a project that is event-driven, but encountering an error. The specific error message I am receiving is: tmpFile = await readFileAsync('tmp.png'); ^^^^^^^^^^^^^ SyntaxError: Unexpec ...

The placement of Bootstrap Datepicker is experiencing issues

I have integrated the Bootstrap Datepicker from Eternicode into my ASP.Net MVC website. While the functionality is working well, I am facing difficulty in positioning the datepicker modal using the orientation option mentioned in the documentation and code ...

Uh oh! We encountered an error: Uncaught (in promise): Error: No routes found for the provided URL segment

There seems to be an issue with the router in my Angular application. I have successfully deployed it on an Apache server for production, and it is being served from the URL www.domain.com/clientng. Everything works fine, but I encounter an error in the br ...