angular - 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);
}
解决方案
如果您知道 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)
数组的功能。
如果你想在某事发生时得到它,那么你只能通过一个事件来做到这一点。
推荐阅读
- css - 弹性和空白:nowrap;孩子不会尊重宽度
- java - Docker build image COPY failed: stat no such file or directory
- amazon-web-services - 如何解决“创建容器任务失败:创建垫片失败:OCI 运行时创建失败:安装无效”错误?
- amazon-web-services - SQS API:sqs:CreateQueue 使用 Cloudformation 在“放大推送”上拒绝访问资源 https://sqs.us-east-1.amazonaws.com/
- symfony - Api 平台 - 从 swagger 中删除自动代码响应描述
- npgsql - YugabyteDB YSQL中的第一个NpgsqlConnection慢
- php - Laravel 中的 Google Calendar API 批量请求
- spring-boot - 为什么在java中迭代数据两次
- spring-boot - 使用放心模拟 mvc 修补端点测试
- python - 为什么变量给我一个 TypeError 但函数没有?