Angular 带标题的省略号指令
我有一个Angle指令,它添加了样式Angular 带标题的省略号指令,angular,angular-directive,Angular,Angular Directive,我有一个Angle指令,它添加了样式文本溢出:省略号;溢出:隐藏;空白:nowrap在ngOnInit中,然后看起来像这样: @Directive({ selector: 'ellipsis' }) class EllipsisDirective { ngAfterViewInit() { const el: HTMLElement = this.el.nativeElement; if (el.offsetWidth < el.scrollWidth) {
文本溢出:省略号;溢出:隐藏;空白:nowrap代码>在ngOnInit
中,然后看起来像这样:
@Directive({ selector: 'ellipsis' })
class EllipsisDirective {
ngAfterViewInit() {
const el: HTMLElement = this.el.nativeElement;
if (el.offsetWidth < el.scrollWidth) {
el.setAttribute('title', el.innerText);
}
}
}
@指令({选择器:'省略号'})
类EllipsisDirective{
ngAfterViewInit(){
const el:HTMLElement=this.el.nativeElement;
如果(标高偏移网络宽度<标高滚动宽度){
el.setAttribute('title',el.innerText);
}
}
}
用法:此处有一些很长的文本
问题:
在某些页面上,布局/组件不会在“导航”上更改,只有数据会更改。目前,该指令没有检测到el.innerText
中的差异,因此保留了旧的.title
属性
我还尝试过使用Input()
,并使用ngOnChanges()
。不过我不想使用输入
我可以让它与输入和设置超时一起工作,但这很难做到。我想我们应该从设置超时开始。答案是使用AfterViewChecked
生命周期事件
后视图已选中
角度检查投射到指令/组件中的内容后作出响应
在ngAfterContentInit()和每个后续ngDoCheck()之后调用
@指令({选择器:'[appEllipsis]})
导出类EllipsisDirective实现OnInit,AfterViewChecked{
private get hasOverflow():布尔值{
const el:HTMLElement=this.el.nativeElement;
返回el.offsetWidth
我想我们应该从这个开始。答案是使用AfterViewChecked
生命周期事件
后视图已选中
角度检查投射到指令/组件中的内容后作出响应
在ngAfterContentInit()和每个后续ngDoCheck()之后调用
@指令({选择器:'[appEllipsis]})
导出类EllipsisDirective实现OnInit,AfterViewChecked{
private get hasOverflow():布尔值{
const el:HTMLElement=this.el.nativeElement;
返回el.offsetWidth
可能重复:可能重复:
@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', '');
}
}
}
}