代码之家  ›  专栏  ›  技术社区  ›  BeetleJuice

角度6:给定elementRef,我能得到viewContainerRef吗?

  •  2
  • BeetleJuice  · 技术社区  · 7 年前

    模板

    <div my-directive></div>
    

    指令

    constructor(vc: ViewContainerRef, el: ElementRef, svc: MyService) {}
    
    useService() {
      this.svc.doWork(vc, el);
    }
    

    所以这项服务需要 ViewContainerRef 和一个 ElementRef . 我必须两个都通过吗?是否有方法从元素引用派生视图容器?如果是这样,我只需要通过 元素元素 到服务,它将从中获取视图容器。

    或者,可以 元素元素 来源于 查看容器引用 ?似乎不可能,因为我假设一个视图容器可以有多个元素。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Reactgular    7 年前

    可以从视图中使用元素引用。它们都引用同一个dom元素。

    constructor(vc: ViewContainerRef, el: ElementRef, svc: MyService) {
         console.log(vc.element.nativeElement === el.nativeElement);
         // prints true
         this.svc.doWork(vc, vc.element);
    }
    
    推荐文章