Home > Software design >  Use MatTooltip with host Angular component
Use MatTooltip with host Angular component

Time:01-14

I'm working with Angular 15.1 & Angular Material 15.1 and I need to use MatTooltip directive with the host component. I know I can create a wrapper and use tooltip attribute - but I need a solution with the host component.

I tried to use MatTooltip like that:

 host: {
    '[attr.matTooltip]': 'some text',
  }

and also with ViewContainerRef, createComponent method and @HostListener, but none of the options did work out

CodePudding user response:

in Angular v15 you can use Directive composition API

@Component({
  selector: 'test',
  template: 'test.html',
  hostDirectives: [{
    directive: MatTooltip,
    inputs: [...],
    outputs: [...],
  }],
})
export class TestComponent { }

CodePudding user response:

I've found an answer on my own, maybe someone will need this too. I will share code pieces below.

 @Component({
  selector: 'test-component',
  template: `
   
    <div>test</div>
  `,
  providers: [MatTooltip],
  styleUrls: ['./test.component.scss'],
})

...

constructor(
    private readonly _tooltip: MatTooltip,
  ) {}

...

@HostListener('mouseenter') onm ouseEnter(): void {
    this._tooltip.message = 'your message';
    this._tooltip.show();
  }

  @HostListener('mouseleave') onm ouseLeave(): void {
    this._tooltip.hide();
  }
  • Related