Home  >  Article  >  Web Front-end  >  How to use TemplateRef in Angular service

How to use TemplateRef in Angular service

青灯夜游
青灯夜游forward
2022-10-08 18:18:331685browse

How to use TemplateRef in Angular service

code repo github.com/rick-chou/a…

Background: I hope to encapsulate my own message service but I don’t know how to use html in the service. The following is one of my solutions

How to use TemplateRef in Angular service

Because I use NG-ZORRO The Notification component is used as the UI layer. [Related tutorial recommendations: "angularjs video tutorial"]

https://ng.ant.design/components/notification/en

NzNotificationService.template The signature is as follows

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

So I need a customized TemplateRef to meet my needs

Idea 1

You can define methods in the service Pass it in from the business component, but there is no difference between using it directly in the business NzNotificationService.template and there is no need for centralized processing

Idea 2

Give service Inject html template

Since you can't write html related code directly in the service, then follow the method of idea 1

Just call the initialization method in advance in a place that has nothing to do with the business

Using ng-template will not generate a real dom node and the service is globally shared. With these two features, we can write the following code

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<emessagecode>>();
  constructor(private notificationService: NzNotificationService) {}

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

  public showMessage(messageCode: EMessageCode) {
    switch (messageCode) {
      case EMessageCode.XXXError:
        return this.notificationService.template(<templateref>>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);
  }
}</templateref></any></emessagecode>

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: `
    <ng-template>
      <div>
        <span></span>
        <span>
          There are XXXError, you must refer to
          <a>something</a>
          to check out
        </span>
      </div>
    </ng-template>
  `,
})
export class MessageServiceVirtualRefComponent implements AfterViewInit {
  @ViewChild('xxx_ref') xxxTemplateRef!: TemplateRef<any>;

  constructor(private messageService: MessageService) {}

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

app.component.html

<app-message-service-virtual-ref></app-message-service-virtual-ref> 
<router-outlet></router-outlet>

For more programming-related knowledge, please visit: Programming Video ! !

The above is the detailed content of How to use TemplateRef in Angular service. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete