【问题标题】:Is any ways to get ElementRef and Component ref in ViewChildren?有什么方法可以在 ViewChildren 中获取 ElementRef 和 Component ref 吗?
【发布时间】:2023-03-26 09:20:01
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript angular dom


    【解决方案1】:

    一种方法是注入:

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

    在父组件中并从子组件中暴露elementRef

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

    然后直接访问elementRef

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

    【讨论】:

      【解决方案2】:

      解决此问题的一种方法是在每个 组件注入 ElementRef 作为公共属性,然后通过迭代组件(来自ViewChildren),你可以访问你想要的一切。

      我的组件.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))
      }
      

      【讨论】:

        【解决方案3】:

        您可以使用 ContentChildren 代替 ViewChildren

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

        我在stackblitz中做了一个例子

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

        【讨论】:

        • 这不是@I.Bond 问题的好答案。使用 ContentChildren 和 ViewChildren 是有区别的。 I.Bond 不使用 ng-content,因此在这种情况下,必须使用 ViewChildren 来访问其子项
        猜你喜欢
        • 2019-12-23
        • 2013-03-26
        • 2020-09-04
        • 1970-01-01
        • 2013-03-05
        • 1970-01-01
        • 2022-01-25
        • 2019-01-11
        • 1970-01-01
        相关资源
        最近更新 更多