import { AfterViewInit, Directive, effect, ElementRef, inject, input, signal, WritableSignal, } from '@angular/core'; import { MatTooltip } from '@angular/material/tooltip'; @Directive({ selector: '[ellipsis]', hostDirectives: [MatTooltip], }) export class Ellipsis implements AfterViewInit { // private readonly templateRef = inject(TemplateRef); // private readonly viewContainer = inject(ViewContainerRef); private readonly elementRef = inject>( ElementRef, ); private readonly tooltip = inject(MatTooltip); private readonly originalText: WritableSignal; public readonly ellipsis = input.required(); public constructor() { this.originalText = signal(this.elementRef.nativeElement.innerHTML); effect(() => { const length = this.ellipsis(); const originalText = this.originalText(); this.tooltip.message = originalText; if (length < 0) { console.warn('Ellipsis Pipe with negative length', length); this.elementRef.nativeElement.innerHTML = ''; return; } if (length < 4) { this.elementRef.nativeElement.innerHTML = '.'.repeat(length); return; } if (originalText.length > length) { this.elementRef.nativeElement.innerHTML = `${originalText.substring(0, length - 3)}...`; return; } }); } public ngAfterViewInit(): void { const originalText = this.elementRef.nativeElement.innerText; this.originalText.set(originalText); } }