offsetHeight和scrollHeight的比较仅在Angular指令中的setTimeout内有效



我需要在Angular指令中检查offsetHeight是否低于scrollHeight。问题是它只能像下面这样工作。我希望避免使用setTimeout。你能给我推荐一些变通办法吗?提前谢谢。

@Directive({
selector: '[appEllipsisDirective]'
})
export class EllipsisDirective implements AfterViewInit {
constructor(private ref: ElementRef) {
}
ngAfterViewInit() {
setTimeout(() => {
if (this.ref.nativeElement.offsetHeight < this.ref.nativeElement.scrollHeight) {
this.init.emit(true);
}
});
}
}
```

我不确定你是否想简单地使用.css来实现

.content
{
display:flex;
flex-wrap: nowrap;
justify-content:space-between;
align-items: flex-start;
width:100%;
}
.line-clam
{
display:block;
overflow:hidden;
}

你可以有

<div class="content">
<div>
<div class="line-clam" [style.max-height]="more?'80px':null">
<span #text >Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua....</span>
</div>
<button *ngIf="text.offsetHeight>80" (click)="more=!more">
{{more?'more':'less'}}
</button>
</div>
<button>one</button>
<button>two</button>
</div>

好吧,你可以在ngOnInit中添加一个window.resize的订阅,说Angular可以制作

ngOnInit()
{
fromEvent(window, 'resize').pipe(debounceTime(1000)).subscribe();
}

您可以在stackblitz 中看到

最新更新