[英]Is any ways to get ElementRef and Component ref in ViewChildren?
我想从视图中获取原生元素和相关组件的列表。
我会尝试做类似的事情,但它不起作用:
@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>
一种方法是注入:
@ViewChildren('element', { read: MyComponent}) private components: QueryList<MyComponent>;
在父组件中并从子组件中公开elementRef
:
class MyComponent {
constructor(public elementRef: ElementRef) {}
}
然后直接访问elementRef
:
this.components.forEach(component => component.elementRef);
解决它的一种方法是将ElementRef作为公共属性注入每个组件,然后通过迭代组件(由ViewChildren
产生),您可以访问您想要的所有内容。
@Component({ /* ... */ })
export class MyComponent {
/* ... */
constructor (public elementRef: ElementRef) { }
/* ... */
}
<virtual-scroller #scroll>
<my-component #element *ngFor="let c of components"></my-component>
</virtual-scroller>
@ViewChildren('element', { read: MyComponent }) private components: QueryList<MyComponent>
/* ... */
ngAfterViewChecked () {
this.components.forEach(c => console.log(c.elementRef))
}
您可以使用 ContentChildren 而不是 ViewChildren
@ContentChildren(YourComponent) components: QueryList<YourComponent>;
我在stackblitz中做了一个例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.