Angular 2 Read More Directive

前端 未结 10 1822
一个人的身影
一个人的身影 2020-12-01 09:41

I need to build a readmore directive in Angular2. What this directive will do is for collapse and expand long blocks of text with \"Read more\" and \"Close\" links. Not on t

10条回答
  •  死守一世寂寞
    2020-12-01 10:11

    import { Component, Input,OnChanges} from '@angular/core';
    @Component({    
        selector: 'read-more',
        template: `
            
    Read {{isCollapsed? 'more':'less'}} ` }) export class ReadMoreDirective implements OnChanges { @Input('text') text: string; @Input('maxLength') maxLength: number = 100; @Input('showToggleButton')showToggleButton:boolean; currentText: string; public isCollapsed: boolean = true; constructor( //private elementRef: ElementRef ) { } toggleView() { this.isCollapsed = !this.isCollapsed; this.determineView(); } determineView() { if (this.text.length <= this.maxLength) { this.currentText = this.text; this.isCollapsed = false; return; } if (this.isCollapsed == true) { this.currentText = this.text.substring(0, this.maxLength) + "..."; } else if(this.isCollapsed == false) { this.currentText = this.text; } } ngOnChanges() { if(!this.validateSource(this.text)) { //throw 'Source must be a string.'; console.error('Source must be a string.'); } else{ this.determineView(); } } validateSource(s) { if(typeof s !== 'string') { return false; } else { return true; } } }

    and usage

提交回复
热议问题