You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中通过上下文向ng-template传方法报错:cancelAction_r127不是函数

Angular对话框模板传递函数报错:cancelAction_r127 is not a function 解决方法

问题重现

你定义的模板代码:

<ng-template #workflowDialog let-data let-ref="dialogRef" let-cancelAction="cancelAction">
    <button (click)="cancelAction()">Cancel</button>
</ng-template>

TS文件中打开对话框的代码:

this.dialogRef = this.dialogService.open(this.workflowDialog, {
    context: {
        cancelAction: () => {this.router.navigate(["edit"], { relativeTo: this.route });},
    }
});

运行时出现错误:cancelAction_r127 is not a function

错误原因

使用let-cancelAction="cancelAction"的方式绑定上下文函数时,Angular模板编译器会将函数转换为内部的表达式绑定标识(如cancelAction_r127),而非直接保留原始函数引用,导致点击按钮时无法找到正确的函数。

解决方法

方法一:简化模板变量声明

将模板中的let-cancelAction="cancelAction"改为let-cancelAction,让Angular自动从context中匹配同名变量:

<ng-template #workflowDialog let-data let-ref="dialogRef" let-cancelAction>
    <button (click)="cancelAction()">Cancel</button>
</ng-template>

TS代码无需修改,保持原有的context传递逻辑即可。

方法二:直接通过上下文对象调用函数

保留let-的赋值逻辑,但通过上下文对象直接访问函数:

<ng-template #workflowDialog let-data let-ref="dialogRef" let-ctx="context">
    <button (click)="ctx.cancelAction()">Cancel</button>
</ng-template>

此方式需确保模板能正确获取到context对象,TS代码同样无需修改。

方法三:改用组件式对话框(可选)

如果业务允许,将对话框改为组件形式,通过dialogRef.componentInstance传递函数:

const dialogRef = this.dialogService.open(WorkflowDialogComponent);
dialogRef.componentInstance.cancelAction = () => {
    this.router.navigate(["edit"], { relativeTo: this.route });
};

组件模板中直接调用cancelAction()即可。


内容的提问来源于stack exchange,提问作者CrazyEight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 13:33:30