我想从 View 中获取 native 元素及其相关组件的列表。
我会尝试做类似的事情,但它不起作用:
@ViewChildren('element', { read: [ElementRef, MyComponent] }) private elements: QueryList<any>; // <-- not work
or
@ViewChildren('element', { read: MyComponent }) private elements: QueryList<MyComponent>;
...
this.elements.first.nativeElement // <-- undefined
这行得通,但看起来不对:
@ViewChildren('element', { read: ElementRef }) private elements: QueryList<ElementRef>;
@ViewChildren('element', { read: MyComponent}) private components: QueryList<MyComponent>;
我的模板简短示例:
<virtual-scroller #scroll>
<my-component #element *ngFor="let c of components"></my-component>
</virtual-scroller>
最佳答案
一种方法是注入(inject):
@ViewChildren('element', { read: MyComponent}) private components: QueryList<MyComponent>;
在父组件中并从子组件中公开 elementRef
:
class MyComponent {
constructor(public elementRef: ElementRef) {}
}
然后直接访问elementRef
:
this.components.forEach(component => component.elementRef);
关于javascript - 有什么方法可以在 ViewChildren 中获取 ElementRef 和 Component ref 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58453108/