cuc*_*uru 4 ng-template angular angular5
我有一个针对不同组件但有一些按钮的通用模板。因此,我创建一个通用组件并使用 ng-template 更改此按钮:
<component-common
[buttonTemplate]="buttonTemplate">
</component-common>
<ng-template #buttonTemplate let-element="element" let-method>
<button (click)="method">
element.name
</button>
</ng-template>
Run Code Online (Sandbox Code Playgroud)
在组件common.component.ts中:
export class ComponentCommonComponent {
@Input() buttonTemplate: TemplateRef<any>;
constructor() { }
test() {
console.log("test called");
}
}
Run Code Online (Sandbox Code Playgroud)
并在html中:
<ng-template
*ngTemplateOutlet="buttonTemplate;context: {method: test(), element:element}">
</ng-template>
Run Code Online (Sandbox Code Playgroud)
我发现的问题是“test”一直被调用,而我只想在单击时调用它,我错过了什么?
改变
{method: test(), element:element}
Run Code Online (Sandbox Code Playgroud)
到
{method: test, element:element}
Run Code Online (Sandbox Code Playgroud)
您不想调用该方法,而只需要方法的引用。
同样在模板中,您应该使用let-method="method"并将其称为method():
<ng-template ... let-method="method">
<button (click)="method()">
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7615 次 |
| 最近记录: |