Ellipsis directive with title

2019-06-04 18:54发布

I have an Angular directive that adds styling text-overflow: ellipsis; overflow: hidden; white-space: nowrap; in ngOnInit and then looks something like this:

@Directive({ selector: 'ellipsis' })
class EllipsisDirective {
  ngAfterViewInit() {
    const el: HTMLElement = this.el.nativeElement;
    if (el.offsetWidth < el.scrollWidth) {
      el.setAttribute('title', el.innerText);
    }
  }
}

Usage: <div ellipsis>Some Very Long Text Here</div>

The problem:
On some pages, the layout/components do not change on a 'navigate', only the data does. Currently the directive does not pick up the difference in el.innerText and thus keeps the old .title property.

I've also tried using an Input() and work with with ngOnChanges(). I'd prefer to not use an input though.

I can make it work with the input and a setTimeout but that can hardly be the way to go.

1条回答
We Are One
2楼-- · 2019-06-04 19:53

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

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

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', '');
      }
    }
  }
}
查看更多
登录 后发表回答