首页 > 解决方案 > 如何在管道中的行html中返回函数名并触发它

问题描述

我正在尝试以角度创建一个阅读更多管道,在使用管道时呈现自定义 HTML。在自定义 HTML 中,我可以通过在管道中传递组件中的方法来访问它吗?

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")
}

问题

标签: angularpipeangular-pipe

解决方案


据我所知,你不能这样做。管道的主要目标是以您需要的任何方式格式化数据。如果您需要呈现 HTML 并将侦听器传递给它,那Component将更适合。

无论如何,您将需要将回调传递给ComponentPipe在路上的某个地方指定它。


推荐阅读