带标题的省略号指令 [英] Ellipsis directive with title

查看:96
本文介绍了带标题的省略号指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

问题:
在某些页面上,布局/组件不会在导航"上更改,只有数据会更改.当前,该指令不会占用el.innerText中的差异,因此保留了旧的.title属性.

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.

我也尝试过使用Input()并与ngOnChanges()一起使用.我宁愿不使用输入.

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

我可以使其与输入和setTimeout一起使用,但这绝不是可行的方法.

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

这篇关于带标题的省略号指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆