我有一个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
财产。
我也尝试过使用Input()
并与ngOnChanges()
合作。我宁愿不使用输入。
我可以使用输入和setTimeout
工作,但这很难成为可行的方法。
我想应该从official docs开始。答案是使用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', '');
}
}
}
}