ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

ng-zorro-antd Message 全局提示完全指南:从服务调用到全局配置与源码级原理

ng-zorro-antd Message 全局提示完全指南:从服务调用到全局配置与源码级原理 UI组件前端【免费下载链接】ng-zorro-antdAngular UI Component Library based on Ant Design项目地址https://gitcode.com/gh_mirrors/ng/ng-zorro-antd点击查看免费下载全局提示Message是 ng-zorro-antdAngular 的 Ant Design 组件库中最常用的轻量级反馈组件之一在页面顶部居中展示一条操作反馈并自动消失全程不打断用户操作。本文将围绕 components/message/doc/index.zh-CN.md 的官方文档结合组件库 components/message 目录下的服务、容器、组件源码与官方 Demo系统讲解NzMessageService的完整 API、NzMessageRef返回对象、NzConfigService全局配置以及消息从创建到销毁的底层实现原理。读完本文你将能熟练在业务中接入各类提示成功、错误、警告、加载中、自定义模板掌握消息的持续时长、悬停暂停、最大堆叠数、顶部位置、RTL 方向等全部配置项并理解其基于 CDK Overlay 的渲染机制。何时使用 Message根据官方文档Message 适用于以下两类典型场景提供成功、警告、错误等操作反馈信息例如表单提交成功、请求失败、数据校验警告以顶部居中、自动消失的方式展示属于不打断用户操作的轻量级提示——与必须用户确认的 Modal、常驻的 Notification 形成明显区别。如果你需要的是持续较长时间、可手动关闭、位置可选的更重量级反馈应优先考虑 notification 组件Message 则定位为用完即走的瞬时提示。快速上手NzMessageService 的 5 个快捷方法NzMessageService是 Message 组件的核心入口在 message.service.ts 中实现。它继承自NzMNServiceNzMessageContainerComponentbase.ts以Injectable({ providedIn: root })方式提供因此无需在模块中显式导入直接依赖注入即可使用。服务提供以下方法使用方式和参数完全一致NzMessageService.success(content, [options])NzMessageService.error(content, [options])NzMessageService.info(content, [options])NzMessageService.warning(content, [options])NzMessageService.loading(content, [options])每个方法都返回一个NzMessageRef对象。以官方 Demo info.ts 为例最基本的用法如下import { Component, inject } from angular/core; import { NzButtonModule } from ng-zorro-antd/button; import { NzMessageService } from ng-zorro-antd/message; Component({ selector: nz-demo-message-info, imports: [NzButtonModule], template: button nz-button nzTypeprimary (click)createBasicMessage()Display normal message/button }) export class NzDemoMessageInfoComponent { private readonly message inject(NzMessageService); createBasicMessage(): void { this.message.info(This is a normal message); } }参数说明参数说明类型默认值content提示内容string \| TemplateRefvoid-options支持设置针对当前提示框的参数见下方表格object-其中content的完整类型定义见 typings.ts为export type NzMessageContentType string | TemplateRefvoid | { $implicit: NzMNComponent; data: NzSafeAny };即既可以传纯字符串也可以传 AngularTemplateRef模板引用。当传入模板时模板上下文中的$implicit指向消息组件实例NzMNComponentdata则对应下方nzData传入的自定义数据。通用 create 方法除了 5 个快捷方法服务还暴露了一个通用方法源码 message.service.tscreate(type: NzMessageType | string, content: NzMessageContentType, options?: NzMessageDataOptions): NzMessageRef官方 Demo other.ts 展示了用它动态生成不同类型消息的写法import { Component, inject } from angular/core; import { NzButtonModule } from ng-zorro-antd/button; import { NzMessageService } from ng-zorro-antd/message; Component({ selector: nz-demo-message-other, imports: [NzButtonModule], template: button nz-button (click)createMessage(success)Success/button button nz-button (click)createMessage(error)Error/button button nz-button (click)createMessage(warning)Warning/button }) export class NzDemoMessageOtherComponent { private readonly message inject(NzMessageService); createMessage(type: string): void { this.message.create(type, This is a message of ${type}); } }注意create的第一个参数同样支持success | info | warning | error | loading之外的自定义字符串类型见NzMessageType定义与NzMessageData.type的类型为NzMessageType | string。options 参数单条消息的细粒度控制调用任意服务方法时可传入第二个可选参数options其类型为NzMessageDataOptions定义于 typings.ts参数说明类型版本nzDuration持续时间(毫秒)当设置为 0 时不消失number-nzPauseOnHover鼠标移上时禁止自动移除boolean-nzAnimate开关动画效果boolean-nzData传递给自定义模板的数据NzSafeAny-nzStyle自定义内联样式NgStyleInterface \| string20.4.0nzClass自定义 CSS classNgClassInterface \| string20.4.0控制显示时长 nzDurationnzDuration控制消息在屏幕上停留的毫秒数当设置为 0 时消息不会自动消失必须由代码手动移除。官方 Demo duration.ts 展示了让消息 10 秒后消失的用法this.message.success(This is a prompt message for success, and it will disappear in 10 seconds, { nzDuration: 10000 });从源码看NzMNComponent.ngOnInitbase.ts会依据nzDuration 0决定是否启动自动关闭定时器autoClose并使用setTimeout在到期后触发销毁当nzDuration 0时autoClose为false消息将常驻直到调用remove。悬停暂停 nzPauseOnHovernzPauseOnHover为true时鼠标移入消息区域mouseenter会暂停倒计时移出mouseleave后继续。源码中的onEnter/onLeavebase.ts实现了精确的剩余时间计算onEnter(): void { if (this.autoClose this.options.nzPauseOnHover) { this.clearEraseTimeout(); this.updateTTL(); // 将剩余存活时间减去已流逝时间 } } onLeave(): void { if (this.autoClose this.options.nzPauseOnHover) { this.startEraseTimeout(); // 按剩余 TTL 重新计时 } }实现上通过eraseTimingStart记录开始时间戳updateTTL()用eraseTTL - Date.now() - eraseTimingStart更新剩余时间从而实现暂停—续走而不延长总时长。开关动画 nzAnimatenzAnimate控制消息的进入/离开动画开关默认开启。在 message.component.ts 中可以看到动画的关键帧定义protected readonly _animationKeyframeMap { enter: MessageMoveIn, leave: MessageMoveOut }; protected readonly _animationClassMap { enter: ant-message-move-up-enter, leave: ant-message-move-up-leave };对应的动画样式定义在 style/animation.less 中。当nzAnimate: false时NzMNComponent.ngOnInit跳过进入动画destroy()也直接派发销毁事件、不等待离场动画结束见 base.ts。自定义模板与数据 nzDatanzData用于向自定义TemplateRef模板传递数据。官方 Demo template.ts 的完整用法import { Component, TemplateRef, ViewChild, inject } from angular/core; import { NzButtonModule } from ng-zorro-antd/button; import { NzMessageComponent, NzMessageService } from ng-zorro-antd/message; Component({ selector: nz-demo-message-template, imports: [NzButtonModule], template: button nz-button nzTypedefault (click)showMessage()Display a custom template/button ng-template #customTemplate let-datadataMy Favorite Framework is {{ data }}/ng-template }) export class NzDemoMessageTemplateComponent { private readonly message inject(NzMessageService); ViewChild(customTemplate, { static: true }) customTemplate!: TemplateRef{ $implicit: NzMessageComponent; data: string; }; showMessage(): void { this.message.success(this.customTemplate, { nzData: Angular }); } }渲染逻辑见 message.component.ts内容通过*nzStringTemplateOutlet指令渲染其上下文为{ $implicit: this, data: instance.options?.nzData }——所以模板内既能用let-datadata拿到nzData传入的数据也能用$implicit拿到消息组件实例。当content是纯字符串时则直接以[innerHTML]输出。自定义内联样式与 class20.4.0从 20.4.0 版本开始支持通过nzStyle与nzClass自定义消息的外层容器样式。类型上两者均可传对象或字符串NgStyleInterface | string/NgClassInterface | string分别绑定到nz-message根节点的[style]与[class]见 message.component.ts。官方 Demo custom-style.tsthis.#messageService.success(This is the content of the notification, { nzStyle: { margin-top: 20vh }, nzClass: custom-class });nzClass会叠加在默认的ant-message-notice类之上nzStyle则以行内样式覆盖适合临时调整单条消息的间距、位置或配色。全局销毁与消息编排remove 与 NzMessageRefremove(id?)按需移除消息NzMessageService.remove(id)用于移除消息传入特定 id 时只移除对应消息当 id 为空时移除所有消息。消息 id 来自各服务方法的返回值NzMessageRef.messageId。其底层实现base.tsremove(id?: string): void { if (this.container) { if (id) { this.container.remove(id); } else { this.container.removeAll(); } } }官方 Demo loading.ts 展示了加载中提示 手动关闭的经典异步场景const id this.message.loading(Action in progress.., { nzDuration: 0 }).messageId; setTimeout(() { this.message.remove(id); }, 2500);这里nzDuration: 0保证加载提示不会自动消失等异步操作完成后通过remove(id)手动收尾——这正是 Message 组件实现不阻塞用户操作异步反馈的标准姿势。NzMessageRefmessageId 与 onClose当你调用NzMessageService.success或其他方法时会返回NzMessageRef对象其类型定义见 typings.tsexport type NzMessageRef PickRequiredNzMessageData, onClose | messageId;等效于官方文档中展示的接口形态export interface NzMessageRef { messageId: string; onClose: Subjectfalse; // 当 message 关闭时它会派发一个事件 }messageId消息的唯一标识可用于remove(id)onClose一个 RxJSSubjectboolean消息关闭无论自动超时还是手动移除时派发事件并结束流。onClose的强大之处在于可以串联多条消息。官方 Demo close.ts 用它实现上一条关闭后自动弹下一条的顺序提示this.message .loading(Action in progress, { nzDuration: 2500 }) .onClose!.pipe( concatMap(() this.message.success(Loading finished, { nzDuration: 2500 }).onClose!), concatMap(() this.message.info(Loading finished is finished, { nzDuration: 2500 }).onClose!) ) .subscribe(() { console.log(All completed!); });每次消息关闭都会触发onClose配合concatMap形成一条加载中 → 成功 → 信息的瀑布流提示链。从容器源码看base.ts无论用户主动销毁还是超时销毁都会执行instance.onClose.next(userAction); instance.onClose.complete();其中userAction为true表示用户手动关闭点击关闭、调用 remove 等。全局配置通过 NzConfigService 定制 Message 行为除了单条消息的options还可以通过NzConfigService做全局级别的配置详情见 全局配置项 文档。全局配置的参数如下参数说明类型默认值nzDuration持续时间(毫秒)当设置为 0 时不消失number3000nzMaxStack同一时间可展示的最大提示数量number7nzPauseOnHover鼠标移上时禁止自动移除booleantruenzAnimate开关动画效果booleantruenzTop消息距离顶部的位置number \| string24nzDirection消息文字方向ltr \| rtl-典型用法是在应用初始化时注入NzConfigService并调用setimport { NzConfigService } from ng-zorro-antd/core/config; const nzConfigService inject(NzConfigService); nzConfigService.set(message, { nzDuration: 4000, nzMaxStack: 5, nzPauseOnHover: false, nzAnimate: true, nzTop: 48 });这些默认值在源码中均有明确定义NZ_MESSAGE_DEFAULT_CONFIGmessage-container.component.ts给出了nzAnimate: true、nzDuration: 3000、nzMaxStack: 7、nzPauseOnHover: true、nzTop: 24、nzDirection: ltr的完整默认集合且与 config.ts 中MessageConfig接口字段一一对应。容器组件的updateConfig()message-container.component.ts采用默认值 → 已存配置 → 全局配置的三层合并策略并通过toCssPixel(this.config.nzTop)把nzTop数值转换为 CSS 像素值绑定到容器顶部。全局配置的变更会通过onConfigChangeEventForComponent(message, ...)实时同步到容器包括nzDirection对应的 RTL class 切换即运行期修改全局配置也能即时生效。关于 nzMaxStack 的行为细节nzMaxStack控制同一时间最多展示的消息数量默认 7。当新增消息导致数量超过上限时最旧的消息会被挤出队列。对应逻辑在容器create()方法中base.tscreate(data: D): RequiredD { const instance this.onCreate(data); if (this.instances.length this.config!.nzMaxStack!) { this.instances this.instances.slice(1); // 移除最早的一条 } this.instances [...this.instances, instance]; this.readyInstances(); return instance; }单条 options 与全局配置的优先级两者通过mergeOptionsbase.ts合并protected mergeOptions(options?: D[options]): D[options] { const { nzDuration, nzAnimate, nzPauseOnHover } this.config!; return { nzDuration, nzAnimate, nzPauseOnHover, ...options }; }即全局配置提供基础默认值单条消息的options通过展开覆盖——单条传入的nzDuration、nzAnimate、nzPauseOnHover优先级最高。源码级原理消息从创建到销毁的完整链路基于 CDK Overlay 的全局渲染NzMessageService继承自NzMNServicebase.ts消息容器并不存在于组件树中而是通过Angular CDK Overlay动态创建首次调用success/error等时createInstancemessage.service.ts通过withContainer创建NzMessageContainerComponentwithContainerbase.ts使用createOverlayRef创建无遮罩hasBackdrop: false、不拦截滚动的 OverlaycreateNoopScrollStrategy并采用createGlobalPositionStrategy全局居中定位策略Overlay 容器的z-index被设置为1010容器以单例方式注册到NzSingletonServicekey 为message-前缀后续调用直接复用同一容器避免重复创建当最后一条消息移除后afterAllInstancesRemoved触发容器被注销、Overlay 被dispose()销毁实现按需创建与释放。这正是 Message 无需在模块中声明、任意组件注入即可弹窗的原因——容器挂载在 Overlay 层与业务组件树完全解耦。消息组件的渲染结构单个消息由NzMessageComponentmessage.component.ts渲染DOM 结构如下div classant-message-notice [class]nzClass [style]nzStyle (mouseenter)onEnter() (mouseleave)onLeave() div classant-message-notice-content div classant-message-custom-content [class]ant-message- instance.type !-- 按类型切换图标 -- nz-icon nzTypecheck-circle / !-- success -- nz-icon nzTypeinfo-circle / !-- info -- nz-icon nzTypeexclamation-circle / !-- warning -- nz-icon nzTypeclose-circle / !-- error -- nz-icon nzTypeloading / !-- loading -- !-- 内容字符串直接 innerHTML模板经 nzStringTemplateOutlet 渲染 -- /div /div /div其中nz-message的根节点绑定了nzStyle/nzClass即 20.4.0 新增的自定义样式能力并注册了mouseenter/mouseleave事件驱动悬停暂停逻辑。不同消息类型通过ant-message-success/info/warning/error/loading类与对应图标区分相关视觉样式集中在 style/index.less 与 style/entry.less 中。容器与实例的管理NzMessageContainerComponentmessage-container.component.ts负责消息队列管理div classant-message [class.ant-message-rtl]dir rtl [style.top]top for (instance of instances; track instance) { nz-message [instance]instance (destroyed)remove($event.id, $event.userAction) / } /div它维护instances数组通过create追加、remove(id)精确移除、removeAll()清空每条消息的destroyed事件回传{ id, userAction }驱动队列更新当队列清空时触发afterAllInstancesRemoved完成 Overlay 释放。dir与top均来自全局配置支持运行期通过NzConfigService热更新subscribeConfigChange。动画与定时器的协作NzMNComponentbase.ts是消息/通知共用的抽象基类完成了时长倒计时与动画调度的核心逻辑进入动画ngOnInit中若nzAnimate开启添加ant-message-move-up-enter类监听animationend并校验动画名是否为MessageMoveIn后移除该类倒计时autoClose nzDuration 0通过initErasestartEraseTimeout用setTimeout调度销毁悬停暂停onEnter/onLeave配合updateTTL精确维护剩余时间离场动画destroy()添加ant-message-move-up-leave类等待MessageMoveOut动画结束后再派发destroyed事件保证视觉上先退场、再移除若nzAnimate: false则跳过动画直接派发。完整接入清单与最佳实践基于以上 API 与源码总结在 ng-zorro-antd 项目中使用 Message 的完整步骤无需导入模块NzMessageService通过providedIn: root全局提供message.service.ts在组件中inject(NzMessageService)或构造函数注入即可按场景选方法success/error/info/warning/loading对应五种语义动态类型用create(type, content, options)设置合理的时长默认 3000ms 自动消失异步任务建议loading(content, { nzDuration: 0 }) 完成后remove(id)或直接利用onClose串联后续提示控制堆叠与位置高频提示场景如批量操作可通过全局配置调低nzMaxStack默认 7或调整nzTop默认 24适配不同的页面头部高度自定义外观需要强调样式时使用nzStyle/nzClass20.4.0需要富内容时使用TemplateRefnzDataRTL 支持通过全局配置nzDirection: rtl切换文字方向容器会自动添加ant-message-rtl类见 message-container.component.ts。总结ng-zorro-antd 的 Message 组件以NzMessageService为核心提供 5 个语义化快捷方法加 1 个通用create方法通过单条optionsnzDuration、nzPauseOnHover、nzAnimate、nzData、nzStyle、nzClass与全局NzConfigServicenzDuration、nzMaxStack、nzPauseOnHover、nzAnimate、nzTop、nzDirection两级配置体系实现了从瞬时提示到异步加载反馈、再到自定义模板的完整能力矩阵。底层基于 CDK Overlay 的全局容器单例、NzMessageRef.onClose事件流与精确的 TTL 倒计时算法保证了组件不打断用户操作的轻量体验。对照官方 Demo 目录components/message/demo中的info、duration、loading、template、custom-style、close、other等示例即可快速落地到真实业务。赞分享UI组件前端【免费下载链接】ng-zorro-antdAngular UI Component Library based on Ant Design项目地址https://gitcode.com/gh_mirrors/ng/ng-zorro-antd点击查看免费下载相关推荐ng-zorro-antd Notification 组件指南NzNotificationService 服务 API、全局配置与源码原理详解ng zorro antd Notification 组件指南NzNotificationService 服务 API、全局配置与源码原理详解 NotificUI组件前端ng-zorro-antd Pagination 分页组件完全指南API 详解、源码原理与全局配置实战ng zorro antd Pagination 分页组件完全指南API 详解、源码原理与全局配置实战 导读 本篇技术指南以 ng zorro antdAnUI组件前端NG-ZORRO Message 全局消息NzMessageService 完整使用指南与源码原理剖析NG ZORRO Message 全局消息NzMessageService 完整使用指南与源码原理剖析 Message 是 NG ZORROAnt DesiUI组件前端上一篇3 步跑通 GoBBlender 与 ZBrush 模型互传下一篇OpenWorker 评审器评测报告解读Muse Spark 1.1 全语料零误放行通过 SHIP GATE创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表