怎么在Angular service中使用TemplateRef

发布时间:2022-10-09 17:41:31 作者:iii
来源:亿速云 阅读:185

这篇“怎么在Angular service中使用TemplateRef”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“怎么在Angular service中使用TemplateRef”文章吧。

NzNotificationService.template 签名如下

template(template: TemplateRef, options?: NzNotificationDataOptions): NzNotificationRef;

所以我需要自定义的 TemplateRef 来满足我的需求

思路一

可以在 service 中定义方法 从业务组件中传入 但是这样和直接在业务中使用 NzNotificationService.template 没有什么区别 也就没有集中处理的必要了

思路二

给 service 注入 html template

既然不能直接在 service 中书写 html 相关代码 那就沿用思路一的方法

只不过事先在一处与业务无关的地方调用初始化的方法

利用 ng-template 不会生成真实的 dom 节点 以及 service 是全局共享 这两个特性三 我们就可以写出如下代码

message.service.ts

import { Injectable, TemplateRef } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd/notification';

export enum EMessageCode {
  XXXError = 1024,
  YYYError = 1025,
}

export const MESSAGE = {
  [EMessageCode.XXXError]: 'XXXError...',
  [EMessageCode.YYYError]: 'YYYError...',
};

@Injectable({
  providedIn: 'root',
})
export class MessageService {
  private templateMap = new Map();
  constructor(private notificationService: NzNotificationService) {}

  // 初始化 templateRef
  public initTemplate(message: EMessageCode, ref: TemplateRef): void {
    this.templateMap.set(message, ref);
  }

  public showMessage(messageCode: EMessageCode) {
    switch (messageCode) {
      case EMessageCode.XXXError:
        return this.notificationService.template(this.templateMap.get(messageCode), {
          nzDuration: 0,
        });
      case EMessageCode.YYYError: {
        return this.notificationService.error('YYYError', MESSAGE[EMessageCode.YYYError]);
      }
    }
  }

  public removeMessage(messageId?: string) {
    this.notificationService.remove(messageId);
  }
}

message-service-virtual-ref.component

import { Component, TemplateRef, ViewChild, AfterViewInit } from '@angular/core';
import { EMessageCode, MessageService } from './message.service';

@Component({
  selector: 'app-message-service-virtual-ref',
  template: `  There are XXXError, you must refer to
          something
          to check out  `,
})
export class MessageServiceVirtualRefComponent implements AfterViewInit {
  @ViewChild('xxx_ref') xxxTemplateRef!: TemplateRef;

  constructor(private messageService: MessageService) {}

  ngAfterViewInit(): void {
    this.messageService.initTemplate(EMessageCode.XXXError, this.xxxTemplateRef);
  }
}

以上就是关于“怎么在Angular service中使用TemplateRef”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

推荐阅读:
  1. 浅析Angular 实现一个repeat指令的方法
  2. angular6.x中ngTemplateOutlet指令的使用示例

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

angular service templateref

上一篇:JavaScript中Number类型常见误区如何解决

下一篇:怎么使用单个标签和CSS实现复杂的棋盘布局

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》