如何移除ngb-timepicker组件默认显示的多余文本
问题原因
你遇到的多余文本是ng-bootstrap timepicker组件内置的无障碍访问辅助文本,默认会通过Bootstrap提供的.sr-only(或高版本Bootstrap的.visually-hidden)类定位到视窗外隐藏,绝大多数情况下该问题的诱因是未正确引入Bootstrap全局CSS,导致隐藏规则未生效。
解决步骤
方案1(优先尝试:修复样式引入)
- 先安装和你当前ng-bootstrap版本匹配的Bootstrap依赖:
# ng-bootstrap 14.x及以上版本对应Bootstrap 5,更低版本对应Bootstrap 4,可根据自己的依赖版本调整 npm install bootstrap@5.x --save
- 打开项目根目录的
angular.json配置文件,找到projects -> 你的项目名 -> architect -> build -> options -> styles配置项,将Bootstrap样式路径加入数组:
"styles": [ "node_modules/bootstrap/dist/css/bootstrap.min.css", "src/styles.scss" ]
- 重启项目开发服务,多余文本即可正常隐藏。
方案2(样式引入正常仍出现问题:手动强制隐藏)
如果已经正确引入Bootstrap样式还是有多余文本,可以通过自定义CSS规则隐藏辅助元素:
- 给timepicker组件添加自定义类名:
<ngb-timepicker class="hide-aux-text" [(ngModel)]="time"></ngb-timepicker>
- 在组件对应样式文件或全局样式文件中添加如下规则:
.hide-aux-text .sr-only, .hide-aux-text .visually-hidden { display: none !important; }
方案3(彻底移除辅助文本生成)
如果你需要从根源上移除这些辅助文本的输出,可以自定义timepicker的i18n服务:
- 新建自定义i18n服务类:
import { Injectable } from '@angular/core'; import { NgbTimepickerI18n } from '@ng-bootstrap/ng-bootstrap'; @Injectable() export class EmptyTimepickerI18n extends NgbTimepickerI18n { override getIncrementAriaLabel(): string { return ''; } override getDecrementAriaLabel(): string { return ''; } }
- 在使用timepicker的模块的providers数组中添加配置:
providers: [ { provide: NgbTimepickerI18n, useClass: EmptyTimepickerI18n } ]
内容的提问来源于stack exchange,提问作者beatrice
相关产品推荐
相关产品推荐

