angular - 如何在管道中的行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")
}
问题:
- 渲染 HTML
button
- 我们可以以某种方式将函数名传递给组件吗?(也许使用 javascript)
- 如果有更好的方法请告诉我
解决方案
据我所知,你不能这样做。管道的主要目标是以您需要的任何方式格式化数据。如果您需要呈现 HTML 并将侦听器传递给它,那Component
将更适合。
无论如何,您将需要将回调传递给Component
或Pipe
在路上的某个地方指定它。
推荐阅读
- java - 用户完成验证码 Selenium 后继续
- mongodb - 尝试在 YAML 文件中使用命令时,使用 docker compose 在 MongoDB 中出错
- c# - 如何在 C# 和实体框架中按日期和公司 ID 对表进行分组
- java - 我怎样才能创建一个流
对象? - android - 问题在于通过 Room 创建数据库
- c - AFL“(奇怪,检查语法!)”
- android - React-native run-android 无法正常工作,因为它找不到任何模拟器 macOS
- sequelize.js - Sequelize 返回结果与 console.log(result) 不同
- excel - 在逗号分隔的列表中查找缺失的数字
- reporting-services - 如何在 Windows Server 2016 上安装 Microsoft.ReportViewer 12.0.0.0?