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

标签 javascript angular dom

我想从 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/

相关文章:

javascript - 对网络上麦克风的影响

javascript - 下拉列表中的keydown事件

javascript - 将数据从一页上的表拉到另一页

javascript - 带有搜索框的单个下拉列表

带有嵌套数组的 Angular 接口(interface)

javascript - 在 Angular 4 中单击时滚动到元素

php - 使用 DOM 和 XPath 从站点地图文件中删除节点

javascript - 在 DOM 中切换 HTML 元素而不复制 HTML

php - 使用 PHP DomDocument 抓取格式错误的 HTML

angular - ag-grid cellRenderer 在值评估后渲染单元格失败