Search code examples
angularangular-ngfor

Angular: How to get object behind *ngFor DOM element without an event?


How do I access the object behind a dom element based by the id of the dom element or something else that does not involve an event?

for example I have:

arr1 = [{a:1, b:2}, {a:5, b:10}, {a:20, b:50}];

<li *ngFor="let obj of arr1; let indexObj=index" id="{{indexObj}}">
    {{obj.a}}
</li>

document.getElementById("1");

But I want to be able to acces the properties a and b associated with the li DOM element

Edit: question was not clear enough so I'll try to expand. what you normally would do

<li *ngFor="let obj of arr1; let indexObj=index" id="{{indexObj}}" (click)="somefunc(obj)">
        {{obj.a}}
 </li>

and then I can acces obj in my function

somefunc(obj) {
    console.log(obj.a);
}

I want to achieve what i'm doing in somefunc without the click event or any other event. so for example I can acces the DOM element li by document.getElementById("1"); or by this.eleRef.nativeElement.querySelector('#1') but I want to have access to the obj associated with the DOM element so I want to be able to do something like this.

somefunc2() {
    let el = document.getElementById("1");
    console.log(obj.a associated with el);
}

Solution

  • If you know the id, then use the array find in your data source.

       const trgItem = arr1.find(item => return item.a === 1);
    

    You should also change your html this way to setup the id properly:

    <ul>
        <li *ngFor="let obj of arr1; let indexObj=index" id="{{indexObj}}">
            {{obj.a}}
        </li>
    <ul>
    

    If you know the index, use the indexOf(0) function of the array.

    If you want to get it when something happens, then you can only do that with an event.