user3629892
user3629892

Reputation: 3046

angular: truncate long text with ellipsis and show more on click

I am using Angular 8, Angular Material and Bootstrap utilities. I have the following code:

          <div class="p-1 text-break"
               *ngSwitchDefault [innerHTML]="cell.value | longText">

This is the longText pipe

  transform(value: any): string {
    if (Array.isArray(value)) {
      return "<div class='text-truncate'>" + value.join(", ") + "</div>";
    }
    return "<div class='text-break'>" + value + "</div>";
  }

}

So basically, I have a two column layout and when the text overflows the width of the column, I want it shown with ellipsis.

It works. However, now I would like to be able to click on a div with ellipsis and open a modal that shows the entire text.

What would be a good way to do this?

Upvotes: 0

Views: 2377

Answers (1)

Mark
Mark

Reputation: 811

I suggest using a component instead of a pipe for this use case like so:

@Component({
    selector: 'truncate-text',
    template: '<div (click)="openModal()" class="text-break" [innerHTML]="text"></div>',
})
export class TruncateTextComponent {
    @Input() text: string|string[];

    openModal() {
        // Use your preferred way of opening a modal and pass this.text as data
    }
}

And to use the component:

<div class="p-1 text-break" *ngSwitchDefault>
    <truncate-text [text]="cell.value"></truncate-text>
</div>

You will need to expand the example to support an array as input.

Upvotes: 1

Related Questions