模板
<div my-directive></div>
指令
constructor(vc: ViewContainerRef, el: ElementRef, svc: MyService) {} useService() { this.svc.doWork(vc, el); }
所以这项服务需要 ViewContainerRef 和一个 ElementRef . 我必须两个都通过吗?是否有方法从元素引用派生视图容器?如果是这样,我只需要通过 元素元素 到服务,它将从中获取视图容器。
ViewContainerRef
ElementRef
元素元素
或者,可以 元素元素 来源于 查看容器引用 ?似乎不可能,因为我假设一个视图容器可以有多个元素。
查看容器引用
可以从视图中使用元素引用。它们都引用同一个dom元素。
constructor(vc: ViewContainerRef, el: ElementRef, svc: MyService) { console.log(vc.element.nativeElement === el.nativeElement); // prints true this.svc.doWork(vc, vc.element); }