Spent half a day working on this...
There's a codepen solution that uses vanilla/alpine js. I've managed to adapt this to Angular:
import { CommonModule } from '@angular/common';
import { Component, ElementRef, Input, ViewChild } from '@angular/core';
@Component({
selector: 'app-expand-if-ellipsis',
templateUrl: './expand-if-ellipsis.component.html',
styleUrl: './expand-if-ellipsis.component.css',
standalone: true,
imports: [CommonModule],
})
export class ExpandIfEllipsisComponent {
@Input() pslText: string = "";
@ViewChild('textEl') textEl: ElementRef|undefined;
expanded: boolean = false;
ellipsis: boolean = false;
ngAfterViewInit(): void {
setTimeout(()=>{
this.setTruncate();
this.expanded = false;
}, 1)
}
toggleExpanded(expanded: boolean){
this.expanded = !expanded;
}
setTruncate() {
const element = this.textEl?.nativeElement;
if(!element) return;
if (
element.offsetHeight < element.scrollHeight ||
element.offsetWidth < element.scrollWidth
) {
this.ellipsis = true;
} else {
this.ellipsis = false;
}
}
}
<div>
<span
#textEl
[class.ellipsis-4]="!expanded"
>{{pslText}}</span>
<div>
<button
*ngIf="ellipsis"
class="button-to-link text--small"
(click)="toggleExpanded(expanded)"
>{{expanded ? 'Minimise comment' : 'Show full comment'}}</button>
</div>
</div>
.ellipsis-4 {
overflow: hidden;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 4;
}
I've tried to create a demo on Stackblitz, but I can't get the darned thing to work with a super simple app. If someone could fix it for me I'd appreciate it. This solution works on my localhost, but some frustrating bugs on stackblitz that I can't figure out.