Looking to create a custom readmore directive in Angular2 that will collapse and expand long blocks of text based on a specified max height, rather than character count. The directive will include "Read more" and "Close" links.
<div read-more [maxHeight]="250px" [innerHTML]="item.details">
</div>
Seeking advice on the most reliable method for getting/setting the height of the element in this scenario.
Any suggestions or guidelines on how to implement this directive would be greatly appreciated.
Similar functionality is needed to what can be seen here: https://github.com/jedfoster/Readmore.js
Solution:
Thanks to Andzhik's help, I have managed to create the following component that fulfills my requirements.
import { Component, Input, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'read-more',
template: `
<div [innerHTML]="text" [class.collapsed]="isCollapsed" [style.height]="isCollapsed ? maxHeight+'px' : 'auto'">
</div>
<a *ngIf="isCollapsable" (click)="isCollapsed =! isCollapsed">Read {{isCollapsed? 'more':'less'}}</a>
`,
styles: [`
div.collapsed {
overflow: hidden;
}
`]
})
export class ReadMoreComponent implements AfterViewInit {
//the text that need to be put in the container
@Input() text: string;
//maximum height of the container
@Input() maxHeight: number = 100;
//set these to false to get the height of the expended container
public isCollapsed: boolean = false;
public isCollapsable: boolean = false;
constructor(private elementRef: ElementRef) {
}
ngAfterViewInit() {
let currentHeight = this.elementRef.nativeElement.getElementsByTagName('div')[0].offsetHeight;
//collapsable only if the contents make container exceed the max height
if (currentHeight > this.maxHeight) {
this.isCollapsed = true;
this.isCollapsable = true;
}
}
}
Usage:
<read-more [text]="details" [maxHeight]="250"></read-more>
If you have any suggestions for improvement, please feel free to share.