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 ?
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 .
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.
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.
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.
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.
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