I have an Angular 6 app; a component method needs access to the viewContainerRef
of any given element in the component's template in order to pass it to a service method. Here is what I'm currently doing. It works but I'm hoping for simpler:
<div #myDiv></div>
<button (click)="doWork()"></button>
And in the component:
@ViewChild('myDiv', {read: ViewContainerRef}) divView: ViewContainerRef;
doWork() {
this.service.work(this.divView);
}
So doWork
needs the viewContainer
. What I'm hoping for is more straightforward, like this:
<div #myDiv></div>
<button (click)="doWork(???)"></button>
Is there some way I can pass in the viewContainer directly from the template into doWork
?
I don't think there is a built-in approach. You could however create a directive that makes the ViewContainerRef available in the template:
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[viewContainer]',
exportAs: 'viewContainer'
})
export class ViewContainerDirective {
constructor(public container: ViewContainerRef) {
}
}
https://stackblitz.com/edit/angular-oydor5?file=src%2Fapp%2Fapp.component.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With