![](/img/trans.png)
[英]How to execute a function, when angular ngFor creates an element in the DOM?
[英]Angular: How to get object behind *ngFor DOM element without an event?
如何根据 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 document.getElementById("1");
或通过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)
函数。
如果您想在发生某些事情时获得它,那么您只能通过事件来做到这一点。
它不起作用,因为您没有插入 ID...
你的 html 应该是:
<li *ngFor="let obj of arr1; index as indexObj" id="{{indexObj}}">
{{obj.a}} //also you had a typo here (ibj instead of obj)
</li>
编辑更新的问题:
由于您知道 id,要检索数组中的项目,您可以执行以下操作:
const arr1 = [{a:1, b:2}, {a:5, b:10}, {a:20, b:50}]; const id = 1; const item = arr1[id]; console.log(item, item.a, item.b);
我创建了stackblitz工作示例供您使用,像这样修改您的组件代码 -
arr1 = [{ a: 1, b: 2 }, { a: 5, b: 10 }, { a: 20, b: 50 }];
ngAfterViewInit() {
const val = Number(document.getElementById('1').innerHTML);
console.log(this.arr1.find(ele => ele.a === val)); // you'll get the object here.
}
您可以使用@ViewChild
和@ViewChildren
获取元素的对象或获取所有子元素
@ViewChildren:
@Component({
selector: 'my-app',
template: `
<alert></alert>
<alert type="danger"></alert>
<alert type="info"></alert>
`,
})
export class App {
@ViewChildren(AlertComponent) alerts: QueryList<AlertComponent>
ngAfterViewInit() {
// Here you get all instances of the alert component
this.alerts.forEach(alertInstance => console.log(alertInstance));
}
}
有关更多信息: https : //angular.io/api/core/ViewChildren
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.