BeetleJuice
BeetleJuice

Reputation: 40916

Angular 6: pass viewContainerRef from template

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?

Upvotes: 5

Views: 3069

Answers (2)

SiliconSoul
SiliconSoul

Reputation: 829

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

Upvotes: 7

Rotem jackoby
Rotem jackoby

Reputation: 22178

You you can access the variable anywhere inside the template. For example:

<div #myDiv></div>
<button (click)="doWork(myDiv)"></button>

Upvotes: 0

Related Questions