在Angular中,可以通过使用上下文将动作传递给ng-template。下面是一个示例解决方案:
在组件的HTML模板中,使用ng-template定义一个具有上下文的模板,并将需要传递的动作作为模板的输入参数:
在组件的 TypeScript 代码中,可以使用ViewChild来获取该ng-template,并将需要传递的动作传递给模板:
import { Component, ViewChild, TemplateRef } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
`
})
export class MyComponent {
@ViewChild('myTemplate') myTemplate: TemplateRef;
performAction(action: string) {
console.log('执行动作:', action);
}
}
在上面的例子中,我们使用*ngTemplateOutlet
将myTemplate引用的动态模板插入到ng-container中,并通过context
参数将action传递给模板。然后,当点击按钮时,performAction
方法将被调用,并输出传递的动作。
通过这种方式,我们可以在ng-template中使用上下文来传递动作或其他数据给模板,并在组件中处理这些动作。