Angular 2 Read More Directive

前端 未结 10 1858
一个人的身影
一个人的身影 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:18

    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: `
            
    Read {{isCollapsed? 'more':'less'}} ` }) 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:

    
    

提交回复
热议问题