Home > Back-end >  How to add title attribute on HTML element with TypeScript
How to add title attribute on HTML element with TypeScript

Time:07-18

I have this span:

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

What I want in TypeScript to add logic here on mouseover to add attribute title on the element, on out method to remove it. Any suggestion?

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);
}

CodePudding user response:

  1. Get the element with id: "first_span" via @ViewChild.

  2. In mouseover method, check toolTip has value and the element (from 1) is existed, then add the "title" attribute.

  3. In out method, check the element (from 1) has existed and the element has the "title" attribute, then remove the "title" attribute from the element.

<span #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);
}

Sample StackBlitz Demo

CodePudding user response:

With the use of Angular Material you could do this with MatTooltipModule : https://material.angular.io/components/tooltip/overview

  • Related