[英]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.