溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Angular service中使用TemplateRef

發(fā)布時間:2022-10-09 17:41:31 來源:億速云 閱讀:203 作者:iii 欄目:web開發(fā)

這篇“怎么在Angular service中使用TemplateRef”文章的知識點大部分人都不太理解,所以小編給大家總結了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“怎么在Angular service中使用TemplateRef”文章吧。

NzNotificationService.template 簽名如下

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

所以我需要自定義的 TemplateRef 來滿足我的需求

思路一

可以在 service 中定義方法 從業(yè)務組件中傳入 但是這樣和直接在業(yè)務中使用 NzNotificationService.template 沒有什么區(qū)別 也就沒有集中處理的必要了

思路二

給 service 注入 html template

既然不能直接在 service 中書寫 html 相關代碼 那就沿用思路一的方法

只不過事先在一處與業(yè)務無關的地方調(diào)用初始化的方法

利用 ng-template 不會生成真實的 dom 節(jié)點 以及 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”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關的知識內(nèi)容,請關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI