1

I'm trying to create a read more pipe in angular, that renders custom HTML when the pipe is used. In the custom HTML can I access method in the component by passing it in the pipe?

readMorePipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'readMore'
})
export class ReadMorePipe implements PipeTransform {

  transform(text: string, length: number = 20, showAll: boolean = false, suffix: string = '...'): any {
    if (showAll) {
      return text;
    }
    if (text.split(" ").length > length) {
      text = text.split(" ").splice(0, length).join(" ") + suffix;
      return `<button (click)="triggerReadMore()" style="color:red;"> //trying to pass function to the component and that function defined in that component 
      ${text}
      </button>`
    }

    return text;
  }

}

Test.component.ts

 <span innerHTML="{{someText | readMore:3:showAll}}"></span>

Test.component.ts

public showAll: boolean = false;
someText: string = "text text text text";
triggerReadMore(){
console.log("do something")
}

problems:

  • rending HTML button
  • can we pass function name to the component somehow?(maybe use javascript)
  • if there any better way please tell me
MahmouD Skafi
  • 370
  • 3
  • 15

2 Answers2

1

As far as I know, you can not do so. The main goal of a pipe is to format data in any way you need to. If you need to render an HTML and pass a listener to it a Component will fit better.

Anyway you will need to pass the callback to the Component or Pipe to specify it somewhere down the road.

Ayzrian
  • 2,279
  • 1
  • 7
  • 14
0

try in Test.component.html

<span [outerHTML]="someText | readMore:3:'showAll'"></span>

Note : However, it is more useful to use directive for these operations.

Onur Özkır
  • 559
  • 3
  • 12