Angular中如何实现鼠标悬停ng-select选项显示完整文本
ng-select下拉选项悬停展示完整文本实现方案
不需要额外遍历选项维护单独的文本数组,利用*ngFor的循环作用域即可精准绑定每个选项的对应内容,以下是两种可直接落地的实现方式:
方案1:原生title属性实现(无额外逻辑,优先推荐)
直接给<ng-option>绑定原生HTMLtitle属性,鼠标悬停时浏览器会自动展示对应选项的完整文本,不需要写任何额外交互逻辑。
修改后的模板代码:
<div class="form-group my-4"> <label class="mb-1">{{'Área_de_Interesse' | translate}}</label> <ng-select [multiple]="false" name="areaInteresse" placeholder="Selecione" formControlName="areaInteresse"> <!-- 给每个选项绑定自身文本到title属性 --> <ng-option *ngFor="let item of areasDeInteresse" [value]="item" [title]="item.nomeAreaInteresse" > {{ item.nomeAreaInteresse }} </ng-option> </ng-select> </div>
对应TS逻辑可以删掉之前遍历存储optionName的冗余代码,简化为:
teste(){ this.dominioService.buscarAreaInteresse().subscribe((data: any) => { // 仅保留过滤启用选项的逻辑即可 this.areasDeInteresse = data.filter(x => x.ativo == true); }); }
实现原理:
*ngFor每渲染一个选项,作用域内的item变量就指向当前这一条独立选项的数据,给每个选项单独绑定自身文本到title属性,悬停时浏览器会自动读取当前选项的title值展示,不需要手动做选项匹配。
方案2:自定义样式Tooltip(适配项目设计风格)
如果浏览器默认的tooltip样式不符合项目UI要求,可以通过悬停事件+自定义模板实现样式可控的提示框:
- 首先在TS中声明变量存储当前悬停的选项:
// 存储当前鼠标悬停的选项 hoveredOption: any = null; teste(){ this.dominioService.buscarAreaInteresse().subscribe((data: any) => { this.areasDeInteresse = data.filter(x => x.ativo == true); }); }
- 修改模板,给选项绑定悬停事件,插入自定义tooltip模板:
<div class="form-group my-4"> <label class="mb-1">{{'Área_de_Interesse' | translate}}</label> <ng-select [multiple]="false" name="areaInteresse" placeholder="Selecione" formControlName="areaInteresse" (mouseleave)="hoveredOption = null" > <ng-option *ngFor="let item of areasDeInteresse" [value]="item" (mouseenter)="hoveredOption = item" > {{ item.nomeAreaInteresse }} <!-- 仅当前悬停项匹配时展示tooltip,建议用唯一id匹配避免重复文本异常 --> <div class="custom-option-tooltip" *ngIf="hoveredOption?.id === item.id"> {{item.nomeAreaInteresse}} </div> </ng-option> </ng-select> </div>
- 添加对应CSS样式控制tooltip效果:
.ng-option { position: relative; } .custom-option-tooltip { position: absolute; left: 12px; top: 100%; z-index: 9999; background-color: rgba(0,0,0,0.8); color: #fff; padding: 6px 10px; border-radius: 4px; font-size: 13px; white-space: nowrap; pointer-events: none; }
内容的提问来源于stack exchange,提问作者Gabriel Oliveira Menezes
相关产品推荐
相关产品推荐

