You need to define a to is able to use <template>
it elsewhere in your app as a TemplateRef
. You can store these TemplateRef
s in a Service and then access them the from any @Directive
or in @Component
your app.
We want to create a service and a component together to store all the templates.
Service
Import {injectable, templateref} from "@angular/core"; @Injectable () Export class Templatesservice { New map<string, templateref<any>>();}
Compoment:
Import {Component, viewchild} from "@angular/core"; import {Templatesservice} from"./shared/services/templates.service"; @Component ({selector:' Template-storage ', Template: '<template #header > `}) Export class Templatestoragecomponent {@ViewChild (' Header ') HeaderTemplate; @ViewChild (' Footer ') FooterTemplate; Constructor (private Service:templatesservice) {} ngafterviewinit () { This. Service.templates.set (' header ', This. HeaderTemplate); This. Service.templates.set (' footer ', This. FooterTemplate); }}
Here, set templates must to present in ' Ngafterviewinit '.
Directive:
Import {Directive, Templateref, viewcontainerref} from "@angular/core"; import {Templatesservice} from".. /services/templates.service "; @Directive ({selector:' [Surround] '}) Export class Surrounddirective {constructor (private template:templateref<any>, private view:viewcontainerref, private Service:templatesservice) {} ngafterviewinit () { This. View.createembeddedview ( This. Service.templates.get (' header ')); This. View.createembeddedview ( This. Template); This. View.createembeddedview ( This. Service.templates.get (' footer ')); }}
[Angular Directive] Create a Template Storage Service in Angular 2