zoukankan      html  css  js  c++  java
  • [Angular Directive] Create a Template Storage Service in Angular 2

    You need to define a <template> to be able to use it elsewhere in your app as a TemplateRef. You can store these TemplateRefs in a Service and then access them from any @Directive or @Component in 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 {
      templates = 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>
            <h1>This is header</h1>
        </template>
        <template #footer>
          <h1>This is the footer</h1>
        </template>
      `
    })
    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'));
      }
    }
  • 相关阅读:
    [Cogs727] [网络流24题#2] 太空飞行计划 [网络流,最小割]
    [Cogs14] [网络流24题#1] 飞行员分配方案 [网络流,最大流,二分图匹配]
    [Poj2112][USACO2003 US OPEN] Optimal Milking [网络流,最大流][Dinic+当前弧优化]
    基本高精度模板
    Dinic模板
    [poj1698]Alice's Chance[网络流]
    [cf 599D] Spongebob and Squares
    [cf 599C] Day at the Beach
    [BZOJ1004]Cards
    [BZOJ1007]水平可见直线
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6291147.html
Copyright © 2011-2022 走看看