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



我想从视图中获取本机元素和相关组件的列表。

我会尝试做这样的事情,但它不起作用:

@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产生(,您可以访问所需的所有内容。

my-component.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>

parent.component.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>;

我在堆栈闪电战中做了一个例子

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

最新更新