繁体   English   中英

有什么方法可以在 ViewChildren 中获取 ElementRef 和 Component ref 吗?

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

@Component({ /* ... */ })
export class MyComponent {
 /* ... */

 constructor (public elementRef: ElementRef) { }

 /* ... */
}

父组件.html

<virtual-scroller #scroll>
  <my-component #element *ngFor="let c of components"></my-component>
</virtual-scroller>

父组件.ts

@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中做了一个例子

https://stackblitz.com/edit/angular-tfjh6e

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM