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