angular - 带标题的省略号指令
问题描述
我有一个 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
但这几乎不是要走的路。
解决方案
我想应该从官方文档开始。答案是使用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', '');
}
}
}
}
推荐阅读
- python - 如何在 64 位窗口中安装 pymqi?
- docker-compose - Docker-Compose 多行键
- modelica - Dymola 模型未在输出中关闭辅助变量的情况下进行初始化
- python - Django Rest 框架请求验证
- javascript - 如何在组件之间传递 v-model 值
- julia - Julia 将 DateTime 添加到 Time 或设置组件
- curl - 尝试使用 Google Cloud KMS 和 API-KEY 加密文本时出现“未验证”
- math - 为什么简化的数学方程比它们在 Julia-Lang 中的运算多得多的等式运行(稍微)慢?
- docker - 在 Mac 上的 Docker 内,无法在带有符号链接的 tarball 上“tar -zxvf”(tar:无法使用时间:没有这样的文件或目录)
- python - python字母和数字中两个列表的笛卡尔积