☰
ng-zorro-antd Button 组件完全指南:五种类型、状态属性与源码级原理解析
2026/9/25 8:03:07 网站建设 项目流程
  • UI组件
  • 前端

【免费下载链接】ng-zorro-antd

Angular UI Component Library based on Ant Design

项目地址:https://gitcode.com/gh_mirrors/ng/ng-zorro-antd
点击查看免费下载

Button 是 ng-zorro-antd(基于 Ant Design 的 Angular 组件库)中最基础、使用频率最高的通用组件之一,其核心职责是"触发一个操作"。本文以 components/button/doc/index.en-US.md 为骨架,结合组件源码 button.component.ts、模块定义 button.module.ts、9 个官方示例 demo 以及测试用例 button.spec.ts,系统讲解按钮的 5 种类型、4 种状态属性、完整 API 参数、形状与尺寸体系,并深入解析nz-button指令的底层实现原理。读完本文,你将能根据业务场景准确选用按钮类型与属性组合,理解nzSize全局配置与表单/紧凑空间的尺寸联动机制,并掌握图标按钮、加载态、禁用态等进阶用法。

什么时候使用按钮(When To Use)

按钮代表一个操作(或一组操作),点击按钮会触发对应的业务逻辑。在 Ant Design 设计体系中,通过视觉层级区分操作优先级是保证界面可用性的关键手段:一个页面(或操作区域)内应当只有一处主操作,其余均为次操作或辅助操作,避免多个视觉焦点互相干扰。

ng-zorro-antd 在nz-button指令上实现了 5 种类型(type)与 4 种附加属性(property),下文逐一展开。

五种按钮类型

在 ng-zorro-antd 中,按钮类型通过nzType输入属性设置,类型定义见 button.component.ts:

export type NzButtonType = 'primary' | 'default' | 'dashed' | 'link' | 'text' | null;
类型视觉定位使用场景
🔵 Primary(primary)主操作,强调色填充表示主要动作,同一区块内最多一个主按钮
⚪️ Default(default,省略nzType即默认)无优先级强调的常规操作表示一系列无优先级差异的动作
🫥 Dashed(dashed)虚线边框常用于"添加"类动作
🔤 Text(text)无边框纯文本最次要的操作
🔗 Link(link)链接样式用于外部链接类操作

官方示例 demo/basic.ts 给出了五类按钮的最小用法:

import { Component } from '@angular/core'; import { NzButtonModule } from 'ng-zorro-antd/button'; @Component({ selector: 'nz-demo-button-basic', imports: [NzButtonModule], template: ` <button nz-button nzType="primary">Primary Button</button> <button nz-button nzType="default">Default Button</button> <button nz-button nzType="dashed">Dashed Button</button> <button nz-button nzType="text">Text Button</button> <a nz-button nzType="link">Link Button</a> ` }) export class NzDemoButtonBasicComponent {}

值得注意的两点:

  • 组件使用 standalone 模式,通过imports: [NzButtonModule]引入按钮模块即可使用nz-button指令;
  • 最后一个示例把nz-button用在<a>元素上,这正是源码中selector: 'button[nz-button], a[nz-button]'(见 button.component.ts)所支持的两种宿主元素形态——<button>用于普通提交/操作,<a>用于跳转链接。两种元素均被视作按钮渲染,样式完全一致。

在源码层面,类型与 CSS 类是一一映射的(见 button.component.ts 的 host 绑定):

host: { class: 'ant-btn', '[class.ant-btn-default]': `nzType === 'default'`, '[class.ant-btn-primary]': `nzType === 'primary'`, '[class.ant-btn-dashed]': `nzType === 'dashed'`, '[class.ant-btn-link]': `nzType === 'link'`, '[class.ant-btn-text]': `nzType === 'text'`, // ... }

组件始终持有基础类ant-btn;当nzType为null(未设置)时,仅保留ant-btn,样式体系将其视作default类型渲染。测试 button.spec.ts 对五类nzType以及null时的类名行为均有断言。

四种附加属性

⚠️ danger:危险操作

nzDanger用于删除、授权撤销等风险性操作,会为按钮套用危险配色。官方示例 demo/danger.ts 展示了它与全部五种类型的组合:

<button nz-button nzType="primary" nzDanger>Primary</button> <button nz-button nzType="default" nzDanger>Default</button> <button nz-button nzType="dashed" nzDanger>Dashed</button> <button nz-button nzType="text" nzDanger>Text</button> <a nz-button nzType="link" nzDanger>Link</a>

在源码中,nzDanger只负责追加ant-btn-dangerous类(见 button.component.ts),具体的红色视觉由组件库的 less 样式体系(components/button/style 目录)实现。测试断言见 button.spec.ts。

👻 ghost:幽灵按钮

nzGhost用于背景复杂(如首页大图、深色底纹)的场景,使按钮背景透明、文字与边框反色,从而在复杂背景上依然清晰可读。官方示例 demo/ghost.ts 在深灰色背景容器上演示了 4 种幽灵按钮:

template: ` <div class="ghost-background"> <button nz-button nzType="primary" nzGhost>Primary</button> <button nz-button nzType="default" nzGhost>Default</button> <button nz-button nzType="dashed" nzGhost>Dashed</button> <a nz-button nzType="link" nzGhost>Link</a> </div> `

源码中nzGhost绑定ant-btn-background-ghost类(见 button.component.ts)。

🚫 disabled:禁用状态

disabled直接沿用原生按钮语义,防止用户与按钮交互。需要注意它同时被用于<button>与<a>两种宿主元素上,源码在 button.component.ts 做了双重处理:

'[attr.tabindex]': 'disabled ? -1 : (tabIndex === null ? null : tabIndex)', '[attr.disabled]': 'disabled || null'
  • 对<button>:透传原生disabled属性;
  • 对<a>:HTML 原生<a>没有disabled属性,因此源码在ngOnInit中通过捕获阶段的 click 监听(fromEventOutsideAngular,即 Angular Zone 之外的监听)拦截事件——当宿主是<a>且disabled为真时,调用event.preventDefault()与event.stopImmediatePropagation()阻止跳转(见 button.component.ts),同时把tabindex设为-1使其移出 Tab 焦点序列,达到与原生禁用一致的可访问性效果。

官方示例 demo/disabled.ts 覆盖了五类按钮 + danger + ghost 的禁用组合演示。

🔃 loading:加载状态

nzLoading在按钮内追加一个加载转圈图标,并阻止重复提交。官方示例 demo/loading.ts 演示了三种典型用法:常驻加载、点击后定时加载(防止重复提交)、圆形加载按钮:

export class NzDemoButtonLoadingComponent { readonly loadings = signal<boolean[]>([false, false]); enterLoading(index: number): void { const update = (index: number, loading: boolean): void => { this.loadings.update(loadings => loadings.map((item, i) => (i === index ? loading : item))); }; update(index, true); setTimeout(() => update(index, false), 3000); } }
<button nz-button nzType="primary" nzLoading> <nz-icon nzType="poweroff" /> Loading </button> <button nz-button nzType="primary" [nzLoading]="loadings()[0]" (click)="enterLoading(0)">Click me!</button>

加载态的源码实现有两处关键逻辑:

  1. 模板注入加载图标(见 button.component.ts):当nzLoading为真时,渲染<span class="ant-btn-icon ant-btn-loading-icon"><nz-icon nzType="loading" /></span>,并追加ant-btn-loading类(L71);
  2. 业务图标隐藏与恢复(见 button.component.ts):若按钮内容里还有nz-icon业务图标,加载时通过Renderer2将其display: none,加载结束后移除该内联样式——这样用户自定义图标与加载图标不会同时出现造成视觉混乱;
  3. 点击拦截:ngOnInit中的 click 捕获监听同时判断nzLoading,加载期间调用preventDefault()与stopImmediatePropagation(),从事件层面杜绝重复提交(L146-L153)。

API:nz-button 完整参数表

nz-button是一个指令(Directive),它接受原生<button>元素支持的所有属性。要获得定制按钮,只需设置nzType/nzShape/nzSize/nzLoading/disabled等输入。完整参数表如下(继承自 components/button/doc/index.en-US.md):

PropertyDescriptionTypeDefaultGlobal Config
[disabled]prevents a user from interacting with the buttonbooleanfalse
[nzGhost]make background transparent and invert text and border colorsbooleanfalse
[nzLoading]set the loading status of buttonbooleanfalse
[nzShape]can be set tocircleroundor omitted'circle'\|'round'-
[nzSize]can be set tosmalllargeor omitted'large'\|'small'\|'default''default'✅
[nzType]can be set toprimarydashedtextlinkor omitted (meaningdefault)'primary'\|'dashed'\|'link'\|'text'-
[nzBlock]option to fit button width to its parent widthbooleanfalse
[nzDanger]set the danger status of buttonbooleanfalse

结合源码补充几个实现级细节:

  • 布尔属性统一使用booleanAttribute转换:nzBlock、nzGhost、nzLoading、nzDanger、disabled五个输入均通过@Input({ transform: booleanAttribute })声明(见 button.component.ts)。这意味着模板里可以直接写<button nz-button nzBlock>(等价于[nzBlock]="true"),也可以写[nzBlock]="someVar",Angular 会自动把字符串属性值转换为布尔;
  • nzSize支持全局配置:nzSize使用了@WithConfig()装饰器,组件模块名常量为'button'(NZ_CONFIG_MODULE_NAME,见 button.component.ts),并注册了配置变更监听onConfigChangeEventForComponent(L122-L126)。因此你可以通过全局配置服务统一设置按钮尺寸,例如在app.config.ts中provideNzConfig({ button: { nzSize: 'large' } }),而无需逐处声明;组件内部ngOnChanges会在nzSize变化时同步内部信号size(L156-L163);
  • 类型与形状的默认值均为null:nzType: NzButtonType = null、nzShape: NzButtonShape = null(L97-L98),null即"省略",渲染为 default 类型与矩形形状。

形状与尺寸体系

nzShape:circle / round

nzShape支持circle(圆形)与round(圆角胶囊形)两种形状,省略时为普通矩形。源码对应类绑定ant-btn-circle/ant-btn-round(见 button.component.ts)。圆形按钮通常用于图标按钮或加载按钮,例如 demo/loading.ts 中的<button nz-button nzLoading nzShape="circle"></button>。

nzSize:large / default / small

nzSize支持large/default/small三档,类型别名NzButtonSize = NzSizeLDSType(见 button.component.ts),对应 CSS 类ant-btn-lg与ant-btn-sm(L68-L69),default 不追加尺寸类。官方示例 demo/size.ts 用nz-radio-group动态切换尺寸,覆盖五种类型、图标按钮、circle/round 形状以及nz-space-compact紧凑组合:

<nz-radio-group [(ngModel)]="size"> <label nz-radio-button nzValue="large">Large</label> <label nz-radio-button nzValue="default">Default</label> <label nz-radio-button nzValue="small">Small</label> </nz-radio-group> <button nz-button [nzSize]="size()" nzType="primary">Primary</button> <button nz-button nzType="primary" [nzSize]="size()" nzShape="round"> <nz-icon nzType="download" /> Download </button> <nz-space-compact [nzSize]="size()"> <button nz-button nzType="primary"> <nz-icon nzType="left" /> Backward </button> <button nz-button nzType="primary"> Forward <nz-icon nzType="right" /> </button> </nz-space-compact>

尺寸的最终生效有一套优先级计算,见 button.component.ts:

protected readonly finalSize = computed(() => { if (this.formSize?.()) { return this.formSize(); } if (this.compactSize) { return this.compactSize(); } return this.size(); });

即:表单内尺寸(NZ_FORM_SIZE,来自表单组件如nz-form-item的尺寸上下文)> 紧凑空间尺寸(NZ_SPACE_COMPACT_SIZE,来自nz-space-compact)> 自身nzSize。这正是示例中nz-space-compact [nzSize]="size()"能统一下拉按钮组尺寸的原因。此外,组件通过hostDirectives: [NzSpaceCompactItemDirective]与providers: [{ provide: NZ_SPACE_COMPACT_ITEM_TYPE, useValue: 'btn' }](L79-L80)把自己注册为紧凑空间中的"按钮型成员",从而获得紧凑模式的间距与圆角联动。

图标按钮与 icon-only 形态

图标按钮是按钮的高频用法。官方示例 demo/icon.ts 演示了纯图标、图标+文字两类组合:

<button nz-button nzType="primary" nzShape="circle"> <nz-icon nzType="search" /> </button> <button nz-button nzType="primary"> <nz-icon nzType="search" /> Search </button>

源码对"纯图标按钮"(icon-only)有专门的自动判定逻辑:组件在afterEveryRender中读取宿主元素子节点,过滤掉display: none的元素后,若可见元素恰好只有 1 个,则置位elementOnly信号(见 button.component.ts),进而通过iconOnly计算属性(L120)为按钮追加ant-btn-icon-only类,让纯图标按钮的宽度收缩为正方形、图标居中。这一机制对图标来源(用户自定义图标或加载图标)都有效:

readonly iconOnly = computed(() => this.elementOnly() && (!!this.iconDir() || !!this.loadingIconDir()));

另外,ngAfterViewInit中的insertSpan()方法(L186-L195)会把按钮内的纯文本节点自动包裹进<span>,这是 antd 按钮在 flex 布局下让文字与图标对齐居中、并对齐加载动画所需的样式前提,开发者无需手动处理。

组合用法:按钮 + 下拉菜单

按钮常与下拉菜单组合形成"操作集"。官方示例 demo/multiple.ts 在一个场景内混排主按钮、次按钮与下拉按钮:

<button nz-button nzType="primary">primary</button> <button nz-button nzType="default">secondary</button> <button nz-button nz-dropdown [nzDropdownMenu]="menu"> Actions <nz-icon nzType="down" /> </button> <nz-dropdown-menu #menu="nzDropdownMenu"> <ul nz-menu> <li nz-menu-item><a>1st item</a></li> <li nz-menu-item><a>2nd item</a></li> <li nz-menu-item><a>3rd item</a></li> </ul> </nz-dropdown-menu>

这印证了官方设计原则:同一区域主按钮(primary)最多一个,其余操作以 default 按钮或下拉按钮承载,避免视觉竞争。同时nz-button指令可与nz-dropdown指令(来自 components/dropdown)在同一宿主元素上叠加使用,互不冲突。

模块引入与依赖说明

按钮模块定义见 button.module.ts,对外导出三个成员:

@NgModule({ imports: [NzButtonComponent], exports: [NzButtonComponent, NzTransitionPatchModule, NzWaveModule] }) export class NzButtonModule {}
  • NzButtonComponent:按钮本体(standalone 组件);
  • NzWaveModule:点击波纹特效模块(来自ng-zorro-antd/core/wave);
  • NzTransitionPatchModule:过渡补丁模块(来自ng-zorro-antd/core/transition-patch),用于旧版浏览器下的动画兼容。

公共 API 通过 public-api.ts 导出组件与模块,index.ts 汇总导出。使用时按 Angular 现代写法在组件级imports中引入NzButtonModule即可(如上面示例所示),同时按钮内部依赖NzIconModule渲染加载图标,若业务中不使用图标可忽略。类型导出(NzButtonType、NzButtonShape、NzButtonSize)同样来自 button.component.ts,可直接用于强类型声明。

源码与测试印证:从类名到行为

以上实现均有测试覆盖,测试文件 button.spec.ts 使用 Vitest + Angular TestBed 编写:

  • 类名绑定测试(L39-L108):逐一断言基础类ant-btn、nzDanger→ant-btn-dangerous、nzGhost→ant-btn-background-ghost、nzLoading→ant-btn-loading、nzBlock→ant-btn-block、五类nzType对应的类型类、nzShape的ant-btn-round/ant-btn-circle、nzSize的ant-btn-lg/ant-btn-sm,以及各输入在默认(false/null)状态下的类名归零行为;
  • 加载态图标测试(L111 起):使用假定时器验证加载时业务图标被隐藏、加载结束后恢复。

如果你在自定义样式时需要覆盖按钮外观,可参考 components/button/style 目录下的 less 源文件,理解ant-btn-*类族的样式变量与嵌套规则;这些样式由根级入口 components/ng-zorro-antd.less 统一聚合,支持按需引入。

小结:选型决策速查

业务诉求推荐配置
页面/区块唯一主操作nzType="primary"(每区最多一个)
无优先级区分的常规操作nzType="default"或不写nzType
添加类动作nzType="dashed"
最次要的辅助操作nzType="text"
外部链接跳转<a nz-button nzType="link">
删除/授权等风险操作nzDanger(可叠加任意类型)
复杂背景上的反色按钮nzGhost
提交中防重复nzLoading(或[nzLoading]动态绑定)
操作暂不可用disabled(对<a>同样生效)
占满父容器宽度nzBlock
圆形/胶囊按钮nzShape="circle"/nzShape="round"
全局统一按钮尺寸全局配置button.nzSize,或表单/紧凑空间上下文自动继承

掌握了这张速查表与本文的源码级原理,你就可以在任何 Angular 业务中精准、高效地使用 ng-zorro-antd 的 Button 组件。

  • UI组件
  • 前端

【免费下载链接】ng-zorro-antd

Angular UI Component Library based on Ant Design

项目地址:https://gitcode.com/gh_mirrors/ng/ng-zorro-antd
点击查看免费下载
上一篇:CANN/ops-math ViewCopy算子接口文档
下一篇:PyTorch面试宝典:The Incredible PyTorch高频考点资源全解析

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询