如何用TypeScript在HTML元素上添加title属性



我有这个span:

<span class="first-span" (mouseover)="mouseover(params)" (mouseout)="out()">
{{params.valueFormatted ? params.valueFormatted : params.value}}
</span>

我想在TypeScript中在mouseover上添加逻辑,在元素上添加属性标题,在out方法上删除它。任何建议吗?

async mouseover(params) {
if (this.toolTip) { return; }
this.handle = setTimeout(() => {
this.checkSaldo(params.value, params.currencyCode ? params.currencyCode : params.currency).then((x) => {
this.toolTip = x;
this.show = true;
// add toolTip value to attribute title and display
return;
});
}, 1500);
}

out() {
this.show = false;
this.toolTip = null;
//remove title attribute
clearTimeout(this.handle);
}
  1. 获取id: "firstrongpan"via@ViewChild.

  2. mouseover方法中,检查toolTip有值并且元素(从1)存在,然后添加"title"属性。

  3. out方法中,检查元素(从1)是否存在并且该元素具有"title"属性,然后删除"title"。属性。

<span #first_span class="first-span" (mouseover)="mouseover(params)" (mouseout)="out()">
{{params.valueFormatted ? params.valueFormatted : params.value}}
</span>
import { ElementRef, ViewChild } from '@angular/core';
@ViewChild('first_span') elem: ElementRef;
async mouseover(params) {
this.handle = setTimeout(() => {
this.checkSaldo(10, 'FRA').then((x) => {
this.toolTip = x;
this.show = true;
if (this.toolTip && this.elem && this.elem.nativeElement)
this.elem.nativeElement.setAttribute('title', this.toolTip);
});
}, 4000);
}
out() {
this.show = false;
this.toolTip = null;
if (this.elem && this.elem.nativeElement) {
let element = this.elem.nativeElement as HTMLElement;
element.attributes.getNamedItem('title') &&
element.attributes.removeNamedItem('title');
}
clearTimeout(this.handle);
}

StackBlitz Demo示例

使用Angular Material,你可以使用MatTooltipModule: https://material.angular.io/components/tooltip/overview

最新更新