【发布时间】:2016-10-15 14:48:19
【问题描述】:
我需要在 Angular2 中构建一个 readmore 指令。该指令将使用“阅读更多”和“关闭”链接折叠和展开长文本块。不是基于字符数,而是基于指定的最大高度。
<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>
如果有任何改进,请随时提出建议。
【问题讨论】:
-
Find currentHeight inside the setTimeout(_ => { ..... }) 将消除一些窗口大小调整问题,同时角度运行变化检测。见stackoverflow.com/questions/38930183/…
标签: angular typescript angular2-template angular2-directives