我需要在Angular2中構建一個readmore指令。這個指令的作用是通過「閱讀更多」和「關閉」鏈接來摺疊和擴展長文本塊。不是以字符數爲基礎,而是基於指定的最大高度。Angular 2更多指令
<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>
如果有可能是任何改進,請隨時提出。
的setTimeout的內部查找currentHeight(_ => {.....})將消除一些窗口在角度運行更改檢測時調整大小問題。看到http://stackoverflow.com/questions/38930183/angular2-expression-has-changed-after-it-was-checked-binding-to-div-width-wi – chenk