Angular 2 Read More Directive
I made a version that uses character length rather than div size.
import { Component, Input, ElementRef, OnChanges} from '@angular/core';
@Component({
selector: 'read-more',
template: `
<div [innerHTML]="currentText">
</div>
<a [class.hidden]="hideToggle" (click)="toggleView()">Read {{isCollapsed? 'more':'less'}}</a>
`
})
export class ReadMoreComponent implements OnChanges {
@Input() text: string;
@Input() maxLength: number = 100;
currentText: string;
hideToggle: boolean = true;
public isCollapsed: boolean = true;
constructor(private elementRef: ElementRef) {
}
toggleView() {
this.isCollapsed = !this.isCollapsed;
this.determineView();
}
determineView() {
if (!this.text || this.text.length <= this.maxLength) {
this.currentText = this.text;
this.isCollapsed = false;
this.hideToggle = true;
return;
}
this.hideToggle = false;
if (this.isCollapsed == true) {
this.currentText = this.text.substring(0, this.maxLength) + "...";
} else if(this.isCollapsed == false) {
this.currentText = this.text;
}
}
ngOnChanges() {
this.determineView();
}
}
Usage:
<read-more [text]="text" [maxLength]="100"></read-more>
I think you'll need a Component
rather then Directive
. Components
makes more sense since you need to add Read more button/link, i.e. update DOM.
@Component({
selector: 'read-more',
template: `
<div [class.collapsed]="isCollapsed">
<ng-content></ng-content>
</div>
<div (click)="isCollapsed = !isCollapsed">Read more</div>
`,
styles: [`
div.collapsed {
height: 250px;
overflow: hidden;
}
`]
})
export class ReadMoreComponent {
isCollapsed = true;
}
Usage:
<read-more>
<!-- you HTML goes here -->
</read-more>