I am starting to learn DOM manipulation in Angular and notice templateRef and its method createEmbeddedView. I am more curious to learn about this method. Now all my question is, how to use the createEmbeddedView of this method
@Component({
selector: 'app-root',
template: `
<ng-template #template>
</ng-template>
`
})
export class AppComponent implements AfterViewChecked {
@ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
constructor() { }
ngAfterViewChecked() {
this._template.createEmbeddedView('this is a embedded view')
}
}
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.
createEmbeddedView(this. template, { $implicit: this. dataSource[i] }); If the input property is specified like this let-item without second part =something , the embedded view treats it as let-item=$implicit so you have to pass a context object with $implicit property.
ElementRef refers to an element of the DOM, whereas TemplateRef represents an embedded template (usually a component template). So to summarize, the template ref can contain several element refs, but the element ref can not contain a template ref.
ViewContainerRef represents a container where one or more views can be attached. The first thing to mention here is that any DOM element can be used as a view container. What's interesting is that Angular doesn't insert views inside the element, but appends them after the element bound to ViewContainer .
You can create an embedded view using createEmbeddedView
method then attach that view to the DOM via ViewContainerRef
:
@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: 'John'});
this.vc.insert(view);
}
}
Or you can create a view using ViewContainerRef
directly:
ngAfterViewChecked() {
this.vc.createEmbeddedView(this._template, {fromContext: 'John'});
}
The context is an object with properties and you can access those properties through let-
bindings.
To learn more read Exploring Angular DOM manipulation techniques using ViewContainerRef and also see this answer.
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