Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get TemplateRef of a component in angular2?

Tags:

angular

I have one component and need to pass your TemplateRef to a directive that will use createEmbeddedView method to replicate this component in a modal.

I tried this, but not had success.

<template let-ref>
    <my-component [myDirective]="ref"></my-component>
</template>

How i do this ?

like image 589
Carlinhos Avatar asked Jan 26 '17 18:01

Carlinhos


People also ask

How do I get ng-template reference in component?

To access the above ng-template in the component or directive, first, we need to assign a template reference variable. #sayHelloTemplate is that variable in the code below. Now, we can use the ViewChild query to inject the sayHelloTemplate into our component as an instance of the class TemplateRef .

How do I get ElementRef from components?

So if you want to get ElementRef from the child that is angular2 component ( VerticeControlComponent ) you need to explicitely tell using read: ElementRef : @ViewChild('scaleControl', {read: ElementRef}) scaleControl: ElementRef; And then inside ngAfterViewInit hook or later you can write this.

What is TemplateRef in Angular?

Descriptionlink. Access a TemplateRef instance by placing a directive on an <ng-template> element (or directive prefixed with * ). The TemplateRef for the embedded view is injected into the constructor of the directive, using the TemplateRef token.

What is TemplateRef and ViewContainerRef?

TemplateRef is an embedded template which you can use in ViewContainerRef. createEmbeddedView to create Embedded View. *ngFor is doing the same, it reads the element as a TemplateRef and injects mutiple times to create view with data. TemplateRef cannot be used as an element for css decorations in .ts.


1 Answers

In the template create a variable at the ng-template level:

<ng-template #templateref>
  <div>Your template content</div>
</ng-template>

In the component use it with @ViewChild, it will be available OnInit.

@Component({
  selector: 'my-component',
  templateUrl: 'my-component.html'
})
export class MyComponent implements OnInit {
  @ViewChild('templateref') public templateref: TemplateRef<any>;

  ngOnInit() {
    console.log(this.templateref);
  }
}

Probably the ViewChild declaration can be simplified, I haven't tested it more than that.

like image 122
Juangui Jordán Avatar answered Sep 18 '22 01:09

Juangui Jordán