>  기사  >  웹 프론트엔드  >  Angular 서비스에서 TemplateRef를 사용하는 방법

Angular 서비스에서 TemplateRef를 사용하는 방법

青灯夜游
青灯夜游앞으로
2022-10-08 18:18:331680검색

Angular 서비스에서 TemplateRef를 사용하는 방법

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

Background: 나만의 메시지 서비스를 캡슐화하고 싶지만 서비스에서 html을 사용하는 방법을 모르겠습니다. 내 솔루션 중 하나 Solution

Angular 서비스에서 TemplateRef를 사용하는 방법 NG-ZORRO의 알림 구성 요소를 UI 레이어로 사용하기 때문입니다. [관련 튜토리얼 추천 : "

angularjs video tutorial

"]

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

NzNotificationService.template 서명은 다음과 같습니다
template(template: TemplateRef, options?: NzNotificationDataOptions): NzNotificationRef;

그래서 내 요구 사항을 충족하려면 사용자 정의된 TemplateRef가 필요합니다NzNotificationService.template 签名如下

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>

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

思路一

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

思路二

给 service 注入 html template

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

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

利用 ng-template

아이디어 1

서비스에서 메서드를 정의하고 비즈니스 구성 요소에서 전달할 수 있지만 이는 비즈니스에서 직접적으로 동일합니다. NzNotificationService.template을 사용할 때 차이가 없으며 중앙 처리가 필요하지 않습니다

아이디어 2

Inject html template into service

서비스에서 직접 HTML 관련 코드를 작성할 수 없다면, 아이디어 1의 방법을 따르세요

단, 아무것도 없는 곳에서 초기화 메소드를 미리 호출해 주면 됩니다. 비즈니스를 수행하세요

ng-template를 사용하면 실제 dom 노드와 서비스가 이 두 기능을 전역적으로 공유하지 않습니다. 다음 코드를 작성할 수 있습니다

message.service.ts🎜
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>
🎜message -service-virtual-ref.comComponent🎜
<app-message-service-virtual-ref></app-message-service-virtual-ref> 
<router-outlet></router-outlet>
🎜app.comComponent.html🎜rrreee🎜 더 많은 프로그래밍 관련 지식을 보려면 🎜Programming Videos🎜를 방문하세요! ! 🎜

위 내용은 Angular 서비스에서 TemplateRef를 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 juejin.cn에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제