Home > Blockchain >  CSS transition with expand/collapse in Angular
CSS transition with expand/collapse in Angular

Time:08-24

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

CodePudding user response:

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  [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

  • Related