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

时间:2019-10-18 14:41:27

标签: javascript angular dom

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

我会尝试做类似的事情,但这是行不通的:

@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>

3 个答案:

答案 0 :(得分:2)

一种方法是注入:

@ViewChildren('element', { read: MyComponent}) private components: QueryList<MyComponent>;

在父组件中,并向子组件公开elementRef

class MyComponent {
    constructor(public elementRef: ElementRef) {}
}

然后直接访问elementRef

this.components.forEach(component => component.elementRef);

答案 1 :(得分:2)

解决此问题的一种方法是将 ElementRef 中的每个组件注入作为公共属性,然后迭代这些组件( ViewChildren的结果),则可以访问所需的所有内容。

my-component.component.ts

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

 constructor (public elementRef: ElementRef) { }

 /* ... */
}

parent.component.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))
}

答案 2 :(得分:0)

您可以使用ContentChildren代替ViewChildren

@ContentChildren(YourComponent) components: QueryList<YourComponent>;

我在stackblitz中做了一个例子

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