Home > Net >  Angular: add a tooltip to a div in runtime
Angular: add a tooltip to a div in runtime

Time:11-08

I create this directive to add a div with some text and I want to show a matTooltoip if the user hovers about the div. how do I manage to add matTooltips to a div at runtime?

import { Directive, ElementRef, Input, OnInit, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appTextBlock]'
})
export class MyDirective implements OnInit {

  constructor(
    private elementRef: ElementRef,
    private renderer: Renderer2) { }

  ngOnInit(): void { }


  public testMethod(toolTip:string){
    var pNode = this.renderer.createElement('div');
   **//this.renderer.addClass(pNode, 'matTooltip=toolTip' );** 

    const text = this.renderer.createText('myText');

    this.renderer.appendChild(pNode,text);
    this.renderer.appendChild(this.elementRef.nativeElement, pNode);
  }

CodePudding user response:

First, you create a directive as below,

import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[hintText]',
})
export class HighlightDirective {
  constructor(private el: ElementRef) {}

  @Input()
  set hintText(value: string[]) {
    this.el.nativeElement.title = value;
  }
}

then use the directive in your DOM element

<div [hintText]="hintText1">Place mouse pointer on me!</div>

<div [hintText]="hintText2">Place mouse pointer on me!</div>

dynamically change your hint text from the component,

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
})
export class AppComponent implements OnInit {     
  hintText1: string;
  hintText2: string;

  ngOnInit(): void {
    this.hintText1 = 'my text title 1';
    this.hintText2 = 'my text title 2';
  }
}
  • Related