Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6: pass viewContainerRef from template

Tags:

angular

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?

like image 901
BeetleJuice Avatar asked Aug 03 '18 15:08

BeetleJuice


1 Answers

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

like image 162
SiliconSoul Avatar answered Sep 29 '22 10:09

SiliconSoul