I am new to angular ,i was reading document ,where i understood that ViewContainerRef will help to append template to dom.
when i read doc on templateREf class https://angular.io/api/core/TemplateRef .I see that class also as createEmbeddedView abstract method.
Can any one help me to understand use case of createEmbeddedView method in Template Ref
Basically, You understood correct that ViewContainerRef will help to append the template to dom.
But when you want to embedd your desired templateRef, then you need to call the method of createEmbeddedView which would take your templateRef as argument and would render the passed templateRef in your ViewContainerRef.
The most basic useCase for this would be directives.
Here I have the directive which would decide whether to render the elment or not based on some conditions. Here I can use *ngIf, but what if I have to use the same logic in multiple files. Here directives are proven best to do so.
Suppose my directive name customDirective getting some input.
So my html having element that needs to be decided to render or not would have the line as below:
<button mat-raised-button *customDirective="'test'">
Upload
</button>
And your directive would be as below mentioned:
@Directive({
selector: '[customDirective]';
})
export class CustomDirective{
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,) {
}
@Input()
set customDirective(condition: string) {
if(condition === 'test'){
this.viewContainer.createEmbeddedView(this.templateRef);}
}
}
So here the viewcontainer would render the desired templateRef. That is in our case the button element.
Edited: As you want to know the use of templateRef.createEmbeddedView, it is used to create the view but this would not attach the view to your DOM. For attaching the created view you have to use the viewContainer.insert.
Now to make clear when to use templateRef.createEmbeddedView here is the example:
@Component({
selector: 'app-root',
template: `
<ng-template #template let-name='fromContext'><div>{{name}}</ng-
template>
<ng-container #vc></ng-container>
`
})
export class AppComponent implements AfterViewChecked {
@ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;
constructor() { }
ngAfterViewChecked() {
const view = this._template.createEmbeddedView({fromContext: 'Joy'});
this.vc.insert(view);
}
}
or you can use the following:
ngAfterViewChecked() {
this.vc.createEmbeddedView(this._template, {fromContext: 'Joy'});
}
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