ARTICLE DETAIL

资讯详情

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

Angular Material Chips 组件 API 完全指南:MatChip 系列组件架构、交互模式与源码剖析

Angular Material Chips 组件 API 完全指南:MatChip 系列组件架构、交互模式与源码剖析 Angular Material Chips 组件 API 完全指南MatChip 系列组件架构、交互模式与源码剖析【免费下载链接】componentsComponent infrastructure and Material Design components for Angular项目地址: https://gitcode.com/GitHub_Trending/co/components导读本文以angular/material/chips公开 API 报告由 API Extractor 生成见 goldens/material/chips/index.api.md为核心骨架结合 src/material/chips/chips.md 官方使用指南与 src/material/chips 目录下的完整源码实现系统梳理 Angular Material Chips 的组件体系。读完本文你将掌握MatChipSet、MatChip、MatChipListbox、MatChipGrid、MatChipRow、MatChipInput等全部公开 API 的职责与用法理解三种交互模式listbox 选择、文本输入、静态内容的底层实现并能正确配置分隔符键、全局默认选项与无障碍属性。一、API 全景从模块到组件的三层结构Chips 是 Angular Material 中用于查看信息、做出选择、过滤内容、输入数据的一组组件。从 API 报告goldens/material/chips/index.api.md可以看到整个包由以下三部分构成一个根模块MatChipsModule它声明并导出全部 13 个指令/组件MatChip、MatChipOption、MatChipRow、MatChipSet、MatChipListbox、MatChipGrid、MatChipInput、MatChipAvatar、MatChipEdit、MatChipEditInput、MatChipRemove、MatChipTrailingIcon、MatChipAction并依赖MatRippleModule与BidiModule。源码见 chips-module.ts公共出口见 public-api.ts。三种容器MatChipSet基础容器、MatChipListbox选择容器继承MatChipSet、MatChipGrid输入容器继承MatChipSet。三种芯片MatChip静态芯片基类、MatChipOption可选中芯片继承MatChip、MatChipRow可编辑/可删除芯片继承MatChip。在源码中继承关系非常清晰MatChipListbox extends MatChipSet见 chip-listbox.tsMatChipGrid extends MatChipSet见 chip-grid.tsMatChipOption extends MatChip见 chip-option.tsMatChipRow extends MatChip见 chip-row.ts。这种基类 派生的设计让三种交互模式共享焦点管理、事件流与状态同步逻辑。此外API 报告还暴露了 7 个注入令牌InjectionTokenMAT_CHIP、MAT_CHIP_AVATAR、MAT_CHIP_EDIT、MAT_CHIP_REMOVE、MAT_CHIP_TRAILING_ICON、MAT_CHIPS_DEFAULT_OPTIONS与MAT_CHIP_LISTBOX_CONTROL_VALUE_ACCESSOR。它们的定义与默认值位于 tokens.ts下文将逐一说明。二、静态内容模式mat-chip-set与mat-chip2.1 基础用法静态芯片永远包裹在容器中使用。最基础的写法是mat-chip-set mat-chip John /mat-chip mat-chip Paul /mat-chip mat-chip James /mat-chip /mat-chip-set默认的mat-chip会应用完整的 Material Design 样式若需要不带样式的裸芯片改用mat-basic-chipAPI 报告中MatChip的选择器为mat-basic-chip, [mat-basic-chip], mat-chip, [mat-chip]。ngOnInit中通过判断宿主元素是否带有mat-basic-chip属性或标签名来决定_isBasicChip标志见 chip.ts。2.2 静态芯片的公开输入InputMatChip的完整输入列表与 API 报告ɵcmp声明一致输入默认值说明rolenull根元素 ARIA role静态场景可手动设为list/listitemid自动生成mat-mdc-chip-xxx芯片唯一 id通过_IdGenerator生成aria-labelnull芯片内容的无障碍标签aria-descriptionnull芯片内容的无障碍描述如编辑提示value芯片文本内容芯片的值默认取.mat-mdc-chip-action-label元素的文本见 chip.tscolorprimary主题色仅 M2 主题生效M3 主题无效果removabletrue是否显示移除样式并触发removed事件highlightedfalse是否以选中强调色高亮芯片disableRipplefalse是否禁用涟漪效果disabledfalse禁用外观禁用状态会与容器的_chipListDisabled合并其中布尔型输入全部通过booleanAttribute转换函数处理见 chip.ts这意味着disabled、removable、highlighted、disableRipple既可以传布尔值也可以仅以属性形式出现。mat-chip disabledOrange/mat-chip2.3 事件与生命周期MatChip暴露两个事件Outputremoved请求移除芯片时触发载荷为MatChipEvent { chip }。编程式调用remove()也会触发但注意它只通知监听者并不会把芯片从 DOM 中删除见 chip.ts。destroyed组件销毁时触发并自动 complete。事件类型MatChipEvent只携带一个chip: MatChip字段。此外 API 报告还列出了内部流_onFocus、_onBlurSubjectMatChipEvent它们通过FocusMonitor监控宿主焦点变化产生是容器级chipFocusChanges/chipBlurChanges的基础见 chip.ts。MatChip实现的生命周期钩子为OnInit, AfterViewInit, AfterContentInit, DoCheck, OnDestroy其中ngDoCheck每次变更检测都会同步涟漪禁用状态见 chip.ts。三、选择模式mat-chip-listbox与mat-chip-option3.1 基础用法与 multiple 属性当需要从列表中单选或多选时使用MatChipListboxMatChipOptionmat-chip-listbox aria-labelselect a shirt size mat-chip-option Small /mat-chip-option mat-chip-option Medium /mat-chip-option mat-chip-option Large /mat-chip-option /mat-chip-listbox若允许多选为 listbox 添加multiple属性。listbox 默认 role 为listbox见 chip-listbox.ts并自动绑定aria-required、aria-disabled、aria-multiselectable、aria-orientation等属性见 chip-listbox.ts。3.2 MatChipListbox 公开输入输出输入默认值说明multiplefalse是否允许多选aria-orientationhorizontal排列方向horizontal \| verticalselectabletrue为false时忽略所有芯片的选中状态compareWith(o1, o2) o1 o2比较选项值与选中值的函数签名(o1: any, o2: any) booleanrequiredfalse是否必选hideSingleSelectionIndicator读取全局默认是否隐藏单选勾选指示valueundefined当前选中值disabled继承false是否禁用整个 listbox输出change: EventEmitterMatChipListboxChange事件载荷包含source与value。listbox 还实现了ControlValueAccessor通过MAT_CHIP_LISTBOX_CONTROL_VALUE_ACCESSOR提供NG_VALUE_ACCESSOR见 chip-listbox.ts因此支持[(ngModel)]与响应式表单。多选模式下value是选中芯片值组成的数组单选模式下是单个值见_propagateChanges实现 chip-listbox.ts。选中集合可通过只读属性selected获取多选返回MatChipOption[]单选返回MatChipOption见 chip-listbox.ts。3.3 MatChipOption 的选择状态机MatChipOption在MatChip基础上增加了selected双向绑定boolean选中状态selectable自身可选择性与容器selectable取与return this._selectable this.chipListSelectable见 chip-option.tsselectionChange: EventEmitterMatChipSelectionChange选中状态变化事件载荷含source、selected、isUserInput。程序化 API 包括select()、deselect()、selectViaInteraction()标记为用户交互触发与toggleSelected(isUserInput?)。核心状态变更统一收敛到私有方法_setSelectedState(isSelected, isUserInput, emitEvent)见 chip-option.ts。单选联动逻辑在 listbox 中实现当非多选模式下某个 chip 被选中时listbox 会遍历并取消其余所有 chip 的选中状态见 chip-listbox.ts。ariaSelectedgetter 依据 WAI ARIA Listbox 规范返回aria-selected字符串见 chip-option.ts。3.4 键盘交互用户可以用方向键在芯片间移动焦点用空格选中/取消选中点击芯片后焦点落在当前芯片键盘导航从该位置继续。容器内部的FocusKeyManagerMatChipAction见 chip-set.ts支持垂直/水平方向导航、Home/End 键跳转。值得注意的是listbox 的_skipPredicate重写为始终返回false即禁用状态的 option 仍可聚焦对齐 WAI ARIA 对复合组件中 listbox 选项的建议但不能被点击见 chip-listbox.ts。四、文本输入模式mat-chip-grid、mat-chip-row与matChipInputFor4.1 完整示例MatChipGrid用于辅助用户文本输入的场景配合MatChipRow与matChipInputFor指令使用mat-form-field mat-chip-grid #myChipGrid [(ngModel)]mySelection aria-labelenter sandwich fillings for (filling of fillings; track filling) { mat-chip-row (removed)remove(filling) {{filling.name}} button matChipRemove mat-iconcancel/mat-icon /button /mat-chip-row } /mat-chip-grid input [matChipInputFor]myChipGrid [matChipInputSeparatorKeyCodes]separatorKeysCodes (matChipInputTokenEnd)add($event) aria-labelAdd sandwich fillings... / /mat-form-field官方文档特别提示输入框应是mat-chip-grid的兄弟节点以确保 Voice Control 等无障碍设备能访问输入框建议为输入框设置合适的aria-label见 chips.md。4.2 MatChipGrid一个完整的 MatFormFieldControlMatChipGrid是 chips 包中能力最完整的组件它同时实现了ControlValueAccessor、MatFormFieldControlany、AfterContentInit、AfterViewInit、DoCheck见 chip-grid.ts。作为MatFormFieldControl它实现了controlType: mat-chip-gridid优先取关联输入框的 id否则用自动生成的mat-chip-grid-xxxempty输入框为空且无任何芯片时才为trueplaceholder优先转发给关联输入框required若未显式设置则探测NgControl上的Validators.required见 chip-grid.tsshouldLabelFloat!empty || focusederrorState/errorStateMatcher通过_ErrorStateTracker管理错误状态stateChanges状态变化流驱动外层 form-field 更新setDescribedByIds/describedByIds把 form-field 的错误提示 id 转发给输入框的aria-describedby。当存在NgControl时构造器会把自身注册为valueAccessor见 chip-grid.ts。_propagateChanges在失焦时把当前所有芯片的 value 以数组形式写入模型并触发change、valueChange与_onChange见 chip-grid.ts。4.3 MatChipRow可编辑、可删除的芯片MatChipRow的选择器为mat-chip-row, [mat-chip-row], mat-basic-chip-row, [mat-basic-chip-row]默认 role 为row见 chip-row.ts。它在MatChip基础上新增editable: boolean开启行内编辑能力edited: EventEmitterMatChipEditedEvent编辑完成事件载荷为{ chip, value }MatChipEditedEvent extends MatChipEventcontentEditInput?: MatChipEditInput内容投影的编辑输入与defaultEditInput?: MatChipEditInput内置默认输入。编辑流程见 chip-row.ts触发方式芯片已聚焦时单击、双击、按 Enter或点击matChipEdit图标_edit()_startEditing记录当前文本值置_isEditing true在afterNextRender中调用_getEditInput().initialize(value)失焦或再按 Enter 时_onEditFinish读取编辑值并发出edited事件随后把焦点还给芯片内容。可编辑芯片的无障碍建议通过aria-description属性告知辅助技术按 Enter 编辑芯片见 chips.md。编辑输入指令MatChipEditInput的选择器是span[matChipEditInput]提供initialize(initialValue)、getValue()、setValue(value)、getNativeElement()四个方法见 chip-edit-input.ts。4.4 键盘交互MatChipGrid中上下方向键在芯片行之间导航它会过滤出与当前活动 action 同属_isPrimary组的 action再在其中移动焦点而不是直接交给 key manager见 chip-grid.ts。Tab 键的处理经过特殊设计_allowFocusEscape临时把容器的tabindex置为 -1 再恢复避免形成焦点陷阱见 chip-set.ts。当焦点在输入框时按 ShiftTab 且存在非禁用芯片会把焦点移到最后一行见 chip-grid.ts。按 Delete/Backspace 键可移除芯片并触发removed事件源码对 Backspace 做了event.repeat防抖防止长按误删多个芯片见 chip.ts。若需删除功能务必实现removed处理器。4.5 与 Autocomplete 组合mat-chip-grid可与mat-autocomplete组合实现自由输入 联想建议。官方文档强调模块导入顺序MatAutocompleteModule必须导入在MatChipsModule之前否则可能出现通过键盘选中建议时仍把输入文本添加为芯片等异常行为见 chips.md。五、MatChipInput输入框与分隔符键MatChipInput是挂在input上的指令选择器为input[matChipInputFor]导出名matChipInput, matChipInputFor见 chip-input.ts。5.1 公开输入输出输入默认值说明matChipInputFor—关联的MatChipGrid设置时会调用registerInput完成注册matChipInputAddOnBlurfalse失焦时是否也触发chipEnd即 token 结束matChipInputSeparatorKeyCodes全局默认[ENTER]触发 chipEnd 的键码列表见下matChipInputDisabledInteractive全局默认false禁用时是否保持可交互输入框呈 readonly 而非 disabledplaceholder占位文本id自动生成输入框 iddisabledfalse是否禁用readonlyfalse是否只读输出matChipInputTokenEnd事件类型MatChipInputEvent { chipInput, value, input }。其中input字段已标记deprecated建议改用chipInput.inputElement见 chip-input.ts。5.2 分隔符键机制默认分隔符键是ENTER见 tokens.ts。separatorKeyCodes支持两种元素纯数字键码如[COMMA, SPACE]SeparatorKey对象{ keyCode: number, modifiers: readonly ModifierKey[] }可要求组合键如{keyCode: ENTER, modifiers: [altKey]}。_isSeparatorKey的匹配逻辑数字键码要求无修饰键按下SeparatorKey则要求指定修饰键精确匹配见 chip-input.ts。命中分隔符后_emitChipEnd发出chipEnd事件并preventDefault。输入框行为细节当输入为空且按下 Backspace 时焦点会转移到最后一个芯片_chipGrid._focusLastChip()同样做了event.repeat防抖见 chip-input.ts。六、图标与操作指令Avatar、Trailing Icon、Remove、Edit芯片通过内容投影提供前后两个图标插槽全部指令定义在 chip-icons.tsMatChipAvatarmat-chip-avatar/[matChipAvatar]前槽头像roleimg用于标识实体如人物头像。所有芯片变体mat-chip、mat-chip-option、mat-chip-row都支持。MatChipTrailingIconmat-chip-trailing-icon/[matChipTrailingIcon]后槽非交互图标aria-hiddentrue。MatChipRemove[matChipRemove]后槽移除按钮rolebutton点击或按 Enter/Space 时调用父芯片的remove()见 chip-icons.ts。MatChipEdit[matChipEdit]前槽编辑按钮rolebutton点击或按 Enter/Space 时触发父芯片_edit()见 chip-icons.ts。MatChipRemove与MatChipEdit都继承自MatChipAction而MatChipAction的禁用状态与父芯片disabled联动_isPrimary标志决定其是否作为主操作参与焦点管理。移除按钮的标准写法官方文档推荐mat-chip-option Orange button matChipRemove aria-labelRemove orange mat-iconcancel/mat-icon /button /mat-chip-option注意matChipRemove必须应用在button元素上绝不能直接放在mat-icon上见 chips.md。七、全局默认配置MAT_CHIPS_DEFAULT_OPTIONSMAT_CHIPS_DEFAULT_OPTIONS是MatChipsDefaultOptions类型的注入令牌可在应用级提供全局默认值bootstrapApplication(MyApp, { providers: [ { provide: MAT_CHIPS_DEFAULT_OPTIONS, useValue: { separatorKeyCodes: [COMMA, SPACE] } } ] });MatChipsDefaultOptions的三个可选字段见 tokens.ts字段类型说明separatorKeyCodesreadonly (number \| SeparatorKey)[] \| ReadonlySetnumber \| SeparatorKey触发 chipEnd 的键码默认[ENTER]hideSingleSelectionIndicatorboolean \| undefined是否全局隐藏单选勾选指示inputDisabledInteractiveboolean \| undefined是否全局让禁用输入框保持可交互此外包内还导出了一组轻量注入令牌MAT_CHIP_AVATAR、MAT_CHIP_TRAILING_ICON、MAT_CHIP_EDIT、MAT_CHIP_REMOVE、MAT_CHIP用于在避免直接引用指令类造成元数据滞留的前提下查询对应实例见 tokens.ts。八、事件体系总览所有公开事件及其载荷汇总如下组件事件载荷类型触发时机MatChipremovedMatChipEvent点击移除按钮 / 按 Delete / 编程调用remove()MatChipdestroyedMatChipEvent组件销毁MatChipOptionselectionChangeMatChipSelectionChange { source, selected, isUserInput }选中状态变化MatChipRoweditedMatChipEditedEvent { chip, value }行内编辑结束MatChipInputchipEndmatChipInputTokenEndMatChipInputEvent { chipInput, value, input }按下分隔符键 / 失焦若addOnBlurMatChipListboxchangeMatChipListboxChange { source, value }用户交互改变选中值MatChipGridchange/valueChangeMatChipGridChange { source, value }失焦时提交芯片集合值容器级还暴露了只读 ObservablechipFocusChanges、chipBlurChanges、chipRemovedChanges、chipDestroyedChangesMatChipSet以及chipSelectionChangesMatChipListbox。这些流通过_getChipStream基于QueryList.changes动态合并所有子芯片的事件见 chip-set.ts新增芯片会自动纳入监听。九、焦点管理FocusKeyManager 与删除重定向MatChipSet的焦点管理核心是FocusKeyManagerMatChipAction把每个芯片的MatChipAction拍平成一个QueryList从而可以芯片内跳转 芯片间移动见 chip-set.ts配置了垂直/水平方向、Home/End 与skipPredicate默认跳过禁用 action用户点击某芯片时chipFocusChanges会把 key manager 的活动项同步到当前 action见 chip-set.ts方向变化时RTL/LTR 切换自动更新水平导航方向。删除焦点重定向当聚焦的芯片被销毁时容器记录其索引_lastDestroyedFocusedChipIndex待芯片真正从QueryList移除后把焦点移到同索引的新芯片若只剩一个禁用芯片则回退到容器本身若列表为空则聚焦容器见 chip-set.ts。MatChipGrid在此基础上增加了清空活动项引用的逻辑避免残留引用见 chip-grid.ts。十、表单集成与验证Chips 与angular/forms完全兼容支持FormsModule、ReactiveFormsModule以及 Angular 新的 signal-based 表单Field类型出现在 API 报告的导入列表中。两种容器的接入方式MatChipListbox通过MAT_CHIP_LISTBOX_CONTROL_VALUE_ACCESSOR提供ControlValueAccessor实现writeValue、registerOnChange、registerOnTouched、setDisabledState见 chip-listbox.ts。valuesetter 写入时会调用_setSelectionByValue按compareWith同步选中状态见 chip-listbox.ts。MatChipGrid在构造器中把自身注册为ngControl.valueAccessor见 chip-grid.ts其writeValue只存储值芯片由开发者自行渲染见 chip-grid.ts。MatChipGrid还完整实现了MatFormFieldControl见第四节因此错误提示、占位符、浮动标签、required校验状态自动探测Validators.required都能与mat-form-field无缝协作。十一、无障碍最佳实践官方文档chips.md对三种模式的 ARIA 要求做了明确约定选择模式listboxMatChipListbox与MatChipGrid都必须通过aria-label或aria-labelledby提供可访问名称listbox 中禁止在mat-chip-option内嵌套其他交互控件否则会劣化辅助技术体验。静态模式用rolelistrolelistitem模拟ul/li语义默认的mat-chip-set与mat-chip不实现任何特定无障碍模式Angular Material 也不打算让它们可交互。移除按钮matChipRemove必须用在button上。单选指示默认 listbox 用勾选标记标识选中项hideSingleSelectionIndicator虽可隐藏但会让用户难以甚至无法视觉识别选中项降低无障碍水平。可编辑芯片通过aria-description提供按 Enter 编辑的操作说明。MatChipInput指令还会把aria-invalid、aria-required、aria-disabled、readonly、required等属性按关联 grid 的状态自动同步到原生输入框见 chip-input.ts。十二、主题样式与垂直排列样式体系遵循 MDC 组件规范基础样式在 chip.scss 与 chip-set.scssM2/M3 主题变量分别在 _m2-chip.scss 与 _m3-chip.scss整体入口为 _chips-theme.scss。color输入仅影响 M2 主题M3 的颜色定制需走 Material 3 的 color variant 体系。默认芯片横向排列需要纵向堆叠时为mat-chip-set、mat-chip-listbox或mat-chip-grid添加mat-mdc-chip-set-stacked类即可。十三、测试支持Component Harnesssrc/material/chips/testing目录提供了完整的测试 Harness 体系见 chip-set-harness.ts、chip-harness.ts、chip-option-harness.ts、chip-row-harness.ts、chip-input-harness.ts、chip-grid-harness.ts、chip-listbox-harness.ts 等涵盖 avatar、edit、edit-input、remove 等子结构。每个 Harness 都配有对应 spec如 chip-listbox-harness.spec.ts组件本身的单元测试则见 chip.spec.ts、chip-listbox.spec.ts、chip-grid.spec.ts、chip-row.spec.ts 等。在组件测试中可通过MatChipsModule或 standalone imports 引入所需组件。结语Angular Material Chips 以一个基类容器 两种派生容器 三种芯片 若干操作指令的紧凑架构覆盖了静态展示、单选多选、自由文本输入、行内编辑四类高频交互场景。其 API 设计的核心思想在于把交互模式差异封装在派生类中而把焦点管理、事件合并、状态同步等通用逻辑沉淀在MatChipSet/MatChip基类里。理解这一分层无论是日常使用mat-chip-listbox做选择器、用mat-chip-grid做标签输入还是阅读 API 报告goldens/material/chips/index.api.md定位某个方法都会更加得心应手。【免费下载链接】componentsComponent infrastructure and Material Design components for Angular项目地址: https://gitcode.com/GitHub_Trending/co/components创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表