首页 > 解决方案 > Angular 6:给定 ElementRef,我可以得到 ViewContainerRef

问题描述

模板

<div my-directive></div>

指示

constructor(vc: ViewContainerRef, el: ElementRef, svc: MyService) {}

useService() {
  this.svc.doWork(vc, el);
}

所以服务需要 aViewContainerRef和 a ElementRef。我必须两个都通过吗?有没有办法从元素 ref 派生视图容器?如果是这样,我只需要传递ElementRef给服务,它就会从中获取视图容器。

或者,可以ElementRefViewContainerRef? 似乎不可能,因为我假设一个视图容器可以有多个元素。

标签: angular

解决方案


您可以使用视图中的元素引用。它们都引用相同的 DOM 元素。

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

推荐阅读