Angular 2 Read More Directive

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

    With the help from Andzhik I am able to build the below component that meets my requirements.

    import { Component, Input, ElementRef, AfterViewInit } from '@angular/core';
    
    @Component({
        selector: 'read-more',
        template: `
            
    Read {{isCollapsed? 'more':'less'}} `, 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; } } }

    Usage:

    
    

提交回复
热议问题