要在Angular中将类方法作为参数传递,可以使用箭头函数来包装类方法,然后将其传递给其他函数或组件。以下是一个示例解决方法:
class MyClass {
myMethod() {
console.log("Class method called");
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `...`,
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
myFunction(callback: () => void) {
// 调用传递的类方法回调函数
callback();
}
}
myFunction
方法,并传递类方法作为参数:
注意:这里使用了 bind
方法来绑定类实例,以确保在调用类方法时,this
上下文正确设置。
MyClass
类并将其分配给组件的属性:export class MyComponent {
myClass = new MyClass();
// ...
}
这样,当点击按钮时,myMethod
方法将被调用。
请注意,上述示例是一个简单的示例,以演示如何将类方法作为参数传递。在实际应用中,您可能需要根据您的需求进行适当的调整和修改。