且构网

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

带有标题的省略号指令

更新时间:2022-10-16 12:10:49

我想人们应该从 官方文档.答案是使用 AfterViewChecked 生命周期事件.

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

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

@Directive({ 选择器: '[appEllipsis]' })导出类 EllipsisDirective 实现 OnInit、AfterViewChecked {私有获取 hasOverflow(): boolean {const el: HTMLElement = this.el.nativeElement;返回 el.offsetWidth 

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.

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', '');
      }
    }
  }
}