How to create read more/less button (Angular)


How about a "Read More" button or link to display overflow text?

Looking for Angular code that can shorten a paragraph if it has more then a certain number of characters?

Here's how to build a read more or less link in Angular.

1. Generate the component

We'll use the Angular CLI to generate a read-more component.

ng generate component read-more

2. The read-more component's code

import { CommonModule } from '@angular/common';
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-read-more',
  template: `
    <div [class.collapsed]="isCollapsed">
      {{ text }}
    </div>
    <div *ngIf="showReadMore" (click)="isCollapsed = !isCollapsed" class="read">{{ isCollapsed ? 'Read more' : 'Read less' }}</div>
    <div *ngIf="!showReadMore" style="padding-bottom: 20px;"></div>
  `,
  styleUrls: ['./read-more.component.css'],
  imports: [ CommonModule ],
  standalone: true
})
export class ReadMoreComponent implements OnChanges {
  @Input() text: string = '';
  showReadMore: boolean = false;
  isCollapsed: boolean = true;

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['text'].currentValue.length > 135) {
      this.showReadMore = true;
    }
  }
}

3. How to use the read-more component

Now that our component is ready we can use it to display a long piece of text like this.

<div class="card-body">
    <h2 class="card-title">Angular Framework</h2>
    <p>
        <span class="badge badge-secondary mr-1">Framework</span>
        <span class="badge badge-secondary mr-1">Web Apps</span>
    </p>
    <askamsa-app-read-more text="Angular is a web framework that empowers developers to build fast, reliable applications. Maintained by a dedicated team at Google, Angular provides a broad suite of tools, APIs, and libraries to simplify and streamline your development workflow. Angular gives you a solid platform on which to build fast, reliable applications that scale with both the size of your team and the size of your codebase."></askamsa-app-read-more>
    <div class="card-actions justify-start mt-4">
        <button class="btn btn-primary" routerLink="/{{avatar.id}}/generate">Interact</button>
         <button class="btn btn-outline btn-secondary" routerLink="/details/{{avatar.id}}">Details</button>
     </div>
</div>

...Read Less

And that is how you build a read more/read less component in Angular.

If you have any questions or comments please reach out.

signature

P.S. Are you skimming?

If so, this article will show you how to create a read more/read less in Angular. It'll take you 2 minutes or less.