[Angular Directive] Create a Template Storage Service in Angular 2

Source: Internet
Author: User
Tags export class

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.