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.