在 NzMessageService 中传递动态 TemplateRef - Angular 15

问题描述 投票:0回答:1

我正在开发一个 Angular 应用程序,其中使用 Ng-Zorro Ant Design 的 NzMessageService 来显示消息。我正在尝试将动态 TemplateRef 传递给 NzMessageService 但面临一些挑战。

这是代码的简化版本:

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

@Injectable({
  providedIn: 'root',
})
export class DynamicMessageService {
  constructor(private messageService: NzMessageService) {}

  showMessage(dynamicText: string | TemplateRef<void>): void {
    // I'm trying to create a dynamic component or view and pass it to NzMessageService
    
    this.messageService.create('error', /* ??? */, { nzDuration: 80000 });
  }
}

dynamicText 可以是字符串或 TemplateRef。我尝试创建动态组件或视图,但遇到类型不匹配的问题。

有人可以提供关于在 Angular 中实现这一目标的最佳方法的指导吗?

html angular angular-components ng-zorro-antd temple
1个回答
0
投票

根据文档,第一个参数用于

templateRef | string

NzMessageService.success(content, [options])
NzMessageService.error(content, [options])
NzMessageService.info(content, [options])
NzMessageService.warning(content, [options])
NzMessageService.loading(content, [options])

content ( 类型: string | TemplateRef ) -> 消息内容

因此,您可以获得模板的视图子级并将其作为第一个参数传递以使其开始工作!

import { Component, ViewChild, TemplateRef } from '@angular/core';

import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'nz-demo-message-info',
  template: ` <button nz-button [nzType]="'primary'" (click)="createBasicMessage()">Display normal message</button> 
  <ng-template #template >
  custom mesage
  <hr/>
  test
</ng-template>
  `,
})
export class NzDemoMessageInfoComponent {
  @ViewChild('template') template!: TemplateRef<void>;
  constructor(private message: NzMessageService) {}

  createBasicMessage(): void {
    this.message.create('error', this.template, { nzDuration: 80000 });
  }
}

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.