What is the method for retrieving array values from an attribute?

I am currently developing an Angular 6 application and I need to pass and retrieve array values dynamically through attributes. Here is the code snippet I have used for this purpose:

HTML:

<ul class="list-unstyled" id="list" [attr.parent_id]="123">
    <li #li class="media p-2 column" *ngFor="let item of items; let i = index;" [attr.items]="item"> {{item.name}} </li>
</ul>

TS:

import { Component, ViewChildren, QueryList, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChildren("li") listElements: QueryList<ElementRef<HTMLLIElement>>;
  name = 'Angular';
  items = [
    { "id": 123, "name": "hello" },
    { "id": 234, "name": "world" }
  ]
  ngAfterViewInit() {
    this.printElements();
    this.listElements.changes.subscribe(_ => this.printElements());
  }

  private printElements() {
    const elements = this.listElements.toArray();
    elements.forEach(element => {
      console.log(element.nativeElement.getAttribute('items'));
    })
  }
}

Working Stackblitz:

https://stackblitz.com/edit/angular-jndtv1

In order to extract the array values from the attribute using only Pure JavaScript/TypeScript without JQuery, I need assistance in getting the correct output instead of "[object object]" when using JSON.stringify.

Answer №1

Here's a workaround to achieve this:

Include the following code in your HTML file:

<ul class="list-unstyled" id="list" [attr.parent_id]="123">
    <li #li class="media p-2 column" *ngFor="let item of items; let i = index;" 
  [attr.items]="item | json"> {{item.name}} </li>
</ul>

In your TypeScript file:

private printElements() {
    const elements = this.listElements.toArray();
    elements.forEach(element => {
      console.log(JSON.parse(element.nativeElement.getAttribute('items')).id);
       console.log(JSON.parse(element.nativeElement.getAttribute('items')).name);
    })
}

Check out the 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

The TypeScript reflection system is unable to deduce the GraphQL type in this case. To resolve this issue, it is necessary to explicitly specify the type for the 'id' property of the 'Address'

import { ObjectType, ID, Int, Field } from 'type-graphql'; @ObjectType() export default class Address { @Field(type => ID) id: String; @Field() type: string; @Field() title: string; @Field() location: string; } More informa ...

When attempting to compile Typescript code, error TS1128 occurs indicating a missing declaration or statement. However, the code functions correctly when executed through a server

Currently, I'm in the process of developing a project using Angular2. As part of this project, I have created a primary Component class which serves as a central piece: import { Component, OnInit} from '@angular/core'; import { submitServi ...

Looking to convert a jQuery function to plain JavaScript code?

Struggling with my homework, I must apologize for any mistakes in my English. My task involves creating a chat using node.js and I found some code snippets on a website "" which I used successfully. The issue now is that the chat relies on old jQuery libr ...

Are Angular 4 auth guards implemented on the server side or the client side? And if they are on the client side, are they vulnerable to

While I am engaged in a project using Angular 4, my expertise lies in angular auth-guards. Here's my query: considering that Angular 4 is primarily a client-sided framework, is it possible to bypass the auth-guard by inspecting the browser window, giv ...

A step-by-step guide on how to verify a selection using JavaScript

Is it possible to validate the select option with JavaScript? For example, if a user selects "Admin," then the page works for admin login. If they select "Vendor," then it works for vendor login. <table class="login_table" width="100%" border="0" cells ...

What could be causing this JavaScript code to run sluggishly in Internet Explorer despite its simple task of modifying a select list?

I am currently developing a multi-select list feature where users can select items and then rearrange them within the list by clicking either an "Up" or "Down" button. Below is a basic example I have created: <html> <head> <tit ...

Access real-time information via JSON

I am facing a logical thinking challenge. Successfully retrieving data from a PHP file via JSON, but now encountering a slight issue. My goal is to retrieve various headlines - main and sub headlines. Each main headline may contain an unknown number of su ...

Using JQUERY to handle event bubbling in the DOM after an AJAX call

I have been attempting to dynamically append content to a specific div using .ajax() and then utilize the new content within a jQuery Dialog. I believe that my usage of .on() is correct, but it appears that the DOM is not being properly updated. Here is t ...

random mongoose response 500

I came across a nodeJS code recently that was supposed to retrieve random documents from my mongoose collection using the mongoose-random plugin. However, whenever I call the findRandom() method, it returns a 500 error. test.js Below is the code snippet: ...

Database not receiving input data from AngularJS form submission

Having some trouble saving form data to the database using angularjs. Not sure what I'm doing wrong. Here's my HTML form: <form id="challenge_form" class="row" > <input type="text" placeholder="Challenge Name" ng-model="ch ...

Retrieving information received from an XML HTTP request in node.js

Currently, I am transmitting text data from a textbox to a node.js express server using XMLHttpRequest: var text = document.getElementById("textBox").value; console.log(text); var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Fire ...

I'm experiencing an issue where my express-session is being reset with every new request, leading me to question if this is related to the development environment I am using (REACT + EXPRESS)

UPDATE - I have ruled out a development environment issue as the same problem persists in production. Thank you for taking the time to look into this. I've searched through numerous questions and attempted various solutions with no success. To give ...

The process of unit testing a component to verify the presence of a specific component on the page

Presenting my straightforward custom component dubbed as NavbarComponent with the selector app-navbar. This component serves as a basic static navbar and is being displayed in app.component.html: app.component.html <app-navbar></app-navbar> &l ...

Tips for implementing a custom filter in an AngularJS JavaScript controller

Can anyone help me with creating a custom filter in an AngularJS JavaScript controller? I need to be able to search for items in an array called segments by their SegmentId. The filter should iterate through the segments array and return the segment that ...

Determining the measurements of an svg path without relying on the bounding box

Is there a way to retrieve the dimensions of an svg path and showcase it within a div without relying on the bounding box method? I've noticed that the bounding box can be buggy in Webkit especially with bezier curves. Just so you know, I am currently ...

Utilizing a modular perspective in JavaScript to load JSON files as a view

I've been working on implementing a modular view approach for retrieving data from a JSON file in my JavaScript code, but I'm facing some issues. The snippet of code where I am trying to load the JSON file is contained within a separate JS file a ...

Image failed to load

Issue Encountered in Browser Console: https://static.food2fork.com/pastaallavodkaa870.jpg.jpg 404 While attempting to display the image on the browser, I am uncertain if the problem lies within my code or with food2fork. Code from index.js: // Alway ...

Numerous Customized Google Maps

On my contact page , I have a Google Map V3 that is styled and mostly functional, except for some sprite image display issues. Now, I need to include the same JSON data in two separate maps on my showrooms page . How can I style multiple maps with differen ...

Angular JS and TypeScript - Issue: ng:areq Invalid Argument "Argument 'XXXXXX' is not a function, received undefined"

Encountering a specific error mentioned in the title. I organized models and controllers into distinct files saved under models and controllers folders respectively. Upon trying to establish a connection between them, I received an error stating "ng:areq ...

Tips for determining the presence of a query string value using JavaScript

Is there a way to detect the presence of q= in the query string using either JavaScript or jQuery? ...