Reputation: 40916
Template
<div my-directive></div>
Directive
constructor(vc: ViewContainerRef, el: ElementRef, svc: MyService) {}
useService() {
this.svc.doWork(vc, el);
}
So the service needs both a ViewContainerRef
and an ElementRef
. Do I have to pass both? Is there a way to derive the view container from the element ref? If so I would only need to pass ElementRef
to the service, and it would fetch the view container from it.
Alternatively, can ElementRef
be derived from ViewContainerRef
? Seems impossible since I assume a single view container can have multiple elements.
Upvotes: 4
Views: 7020
Reputation: 54801
You can use the element reference from the view. They both reference the same DOM element.
constructor(vc: ViewContainerRef, el: ElementRef, svc: MyService) {
console.log(vc.element.nativeElement === el.nativeElement);
// prints true
this.svc.doWork(vc, vc.element);
}
Upvotes: 5