首页 > 解决方案 > Angular:如何在没有事件的情况下获取 *ngFor DOM 元素后面的对象?

问题描述

如何根据 dom 元素的 id 或不涉及事件的其他内容访问 dom 元素后面的对象?

例如我有:

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");

但我希望能够访问与 li DOM 元素关联的属性 a 和 b

编辑:问题不够清楚,所以我会尝试扩展。你通常会做什么

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

然后我可以在我的函数中访问 obj

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

somefunc我想在没有点击事件或任何其他事件的情况下实现我正在做的事情。因此,例如,我可以通过document.getElementById("1");或通过访问 DOM 元素 li,this.eleRef.nativeElement.querySelector('#1')但我想访问与 DOM 元素关联的 obj,所以我希望能够做这样的事情。

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

标签: angularangular-ngfor

解决方案


如果您知道 id,则find在数据源中使用该数组。

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

您还应该以这种方式更改 html 以正确设置 id:

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

如果您知道索引,请使用indexOf(0)数组的功能。

如果你想在某事发生时得到它,那么你只能通过一个事件来做到这一点。


推荐阅读