0

I have referred to other questions on SO related to expand/collapse, but the solutions are mostly based on setting height CSS property. I have tried, but those solutions are not applicable to my use case.

I have long string, if its length exceeds a limit I want to clip it by default and expand it by clicking on "Show more". On clicking "Show less", it should collapse the long string. I have implemented the functionality but the transition from collapsed to expanded does not have animation and looks jarring.

I would like to know how the collapsed/expanded transitions could made nicer.

Here's stackblitz reproduction of the same: https://stackblitz.com/edit/angular-ivy-exalqr?file=src/app/app-expand/app-expand.component.ts

Phalgun
  • 1,181
  • 2
  • 15
  • 42
  • Actions of this type are usually done with design libraries like Bootstrap But here you have an answer, how can you do it yourself, without a library https://stackoverflow.com/a/55879513/11523006 – n w Aug 22 '22 at 20:24
  • That answer is bootstrap specific, however I can't use bootstrap. Thanks for your comment. – Phalgun Aug 23 '22 at 03:49

1 Answers1

1

Just use the below css, where you set the width to the number of characters you want to show.

html

.cropper-wrapper {
  width: 95px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  transition: all 1s ease-in-out;
}

.isCollapsed {
  width: 100% !important;
  display: inline-block;
}

css

<span class="cropper-wrapper" [ngClass]="{ isCollapsed: !isCollapsed }"
  >{{ str }}
</span>
<span (click)="toggle()">{{ isCollapsed ? 'Show More' : 'Show less' }}</span>

ts

import {
  ChangeDetectionStrategy,
  Component,
  Input,
  OnInit,
} from '@angular/core';

@Component({
  selector: 'app-expand',
  templateUrl: './app-expand.component.html',
  styleUrls: ['./app-expand.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppExpandComponent implements OnInit {
  isCollapsed = false;
  @Input() str;

  private _input: string = '';
  private _originalInput: string = '';

  constructor() {}

  ngOnInit() {
    this.toggle();
  }

  toggle() {
    if (this.isCollapsed) {
      this._input = this._originalInput;
    } else {
      if (this._originalInput.length > 10) {
        this._input = this._originalInput.substring(0, 10) + '...';
      }
    }
    this.isCollapsed = !this.isCollapsed;
  }
}

forked stackblitz

Naren Murali
  • 19,250
  • 3
  • 27
  • 54