首页 > 解决方案 > 带标题的省略号指令

问题描述

我有一个 Angular 指令,它添加了样式text-overflow: ellipsis; overflow: hidden; white-space: nowrap;ngOnInit然后看起来像这样:

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

用法:<div ellipsis>Some Very Long Text Here</div>

问题:
在某些页面上,布局/组件在“导航”时不会改变,只有数据会改变。目前,该指令没有获取差异el.innerText,因此保留了旧.title属性。

我也尝试过使用 anInput()并使用 with ngOnChanges()。我宁愿不使用输入。

我可以使它与输入和 a 一起工作,setTimeout但这几乎不是要走的路。

标签: angularangular-directive

解决方案


我想应该从官方文档开始。答案是使用AfterViewChecked生命周期事件。

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

在 ngAfterContentInit() 和每个后续的 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', '');
      }
    }
  }
}

推荐阅读