[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'));
  }
}
复制代码

 

posted @   Zhentiw  阅读(309)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2015-01-16 [MODx] 10. Using Babel for Muti-languages support
点击右上角即可分享
微信分享提示