Diretiva Angular 2 Leia mais
Preciso criar uma diretiva readmore no Angular2. O que esta diretiva fará é recolher e expandir longos blocos de texto com os links "Leia mais" e "Fechar". Não com base na contagem de caracteres, mas com base na altura máxima especificada.
<div read-more [maxHeight]="250px" [innerHTML]="item.details">
</div>
Alguém pode, por favor, orientar qual seria a maneira mais confiável de obter / definir a altura do elemento para este caso específico.
Qualquer orientação sobre como essa diretiva específica poderia ser implementada também seria muito apreciada.
Eu preciso construir algo assimhttps://github.com/jedfoster/Readmore.js
Solução:
Com a ajuda de Andzhik, sou capaz de construir o componente abaixo que atende aos meus requisitos.
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;
}
}
}
Uso:
<read-more [text]="details" [maxHeight]="250"></read-more>
Se houver alguma melhoria, não hesite em sugerir.