且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带标题的省略号指令

更新时间:2022-01-06 22:15:10

我想应该从

I guess one should've started with the official docs. The answer is using the AfterViewChecked lifecycle event.

AfterViewChecked
Angular检查投影到指令/组件中的内容后响应.

AfterViewChecked
Respond after Angular checks the content projected into the directive/component.

在ngAfterContentInit()和随后的每个ngDoCheck()之后调用.

Called after the ngAfterContentInit() and every subsequent ngDoCheck().

@Directive({ selector: '[appEllipsis]' })
export class EllipsisDirective implements OnInit, AfterViewChecked {
  private get hasOverflow(): boolean {
    const el: HTMLElement = this.el.nativeElement;
    return el.offsetWidth < el.scrollWidth;
  }

  constructor(
    private el: ElementRef,
    @Inject(PLATFORM_ID) private platformId: any,
  ) {}

  ngOnInit() {
    // class overflow: text-overflow: ellipsis; overflow: hidden; white-space: nowrap;
    this.el.nativeElement.classList.add('overflow');
  }

  ngAfterViewChecked() {
    const isBrowser = isPlatformBrowser(this.platformId);
    if (isBrowser) {
      if (this.hasOverflow) {
        this.el.nativeElement.setAttribute('title', this.el.nativeElement.innerText);
      } else {
        this.el.nativeElement.setAttribute('title', '');
      }
    }
  }
}