Мне нужно создать директиву readmore в Angular2. Эта директива будет заключаться в том, чтобы свернуть и расширить длинные блоки текста с помощью ссылок "Подробнее" и "Закрыть". Не на основе количества символов, а на основе указанной максимальной высоты.
<div read-more [maxHeight]="250px" [innerHTML]="item.details">
</div>
Может ли кто-нибудь указать, что было бы самым надежным способом получить/установить высоту элемента для этого конкретного случая.
Также будут высоко оценены любые рекомендации о том, как эта конкретная директива может быть реализована.
Мне нужно построить что-то вроде этого https://github.com/jedfoster/Readmore.js
Решение:
С помощью Andzhik я могу создать нижеуказанный компонент, соответствующий моим требованиям.
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;
}
}
}
Использование:
<read-more [text]="details" [maxHeight]="250"></read-more>
Если могут быть какие-либо улучшения, пожалуйста, не стесняйтесь предлагать.