如何在 ShadowDOM 中通过 id 查找元素?
How to find elements by id in ShadowDOM?
如何获取对封装设置为 ShadowDOM 的 Angular 组件中元素的引用?
const element = document.getElementById(id);
例如,returns 空
编辑:添加了 html 片段
<div *ngFor='let item of items' [attr.id]='item.key'>
.....
</div>
我需要引用每个创建的 div。
使用模板变量是可行的,但据我所知,您不能动态生成模板变量。
例如
<div #myTarget> ... </div>
有效
您的代码与 ShadowDOM 完全无关,您不应该在 Angular 中按 ID 选择元素,因为那是一个 anti-pattern。相反,请在您的 TypeScript 代码中使用 the ViewChildren()
selector!
class SomeCmp implements AfterViewInit {
@ViewChildren('myItem') items!: QueryList<ElementRef>;
ngAfterViewInit(): void {
console.log(`I have ${this.items.length} items!`);
}
}
<div *ngFor='let item of items' #myItem>
.....
</div>
如何获取对封装设置为 ShadowDOM 的 Angular 组件中元素的引用?
const element = document.getElementById(id);
例如,returns 空
编辑:添加了 html 片段
<div *ngFor='let item of items' [attr.id]='item.key'>
.....
</div>
我需要引用每个创建的 div。
使用模板变量是可行的,但据我所知,您不能动态生成模板变量。
例如
<div #myTarget> ... </div>
有效
您的代码与 ShadowDOM 完全无关,您不应该在 Angular 中按 ID 选择元素,因为那是一个 anti-pattern。相反,请在您的 TypeScript 代码中使用 the ViewChildren()
selector!
class SomeCmp implements AfterViewInit {
@ViewChildren('myItem') items!: QueryList<ElementRef>;
ngAfterViewInit(): void {
console.log(`I have ${this.items.length} items!`);
}
}
<div *ngFor='let item of items' #myItem>
.....
</div>