在Angular中,你可以在公共方法中调用按钮上的函数,可以通过以下两种方法实现:
在按钮上定义一个事件绑定符号(@),把按钮的函数绑定到一个公共方法上。然后在公共方法中,调用该绑定的函数。
HTML模板:
组件类:
export class AppComponent {
buttonClick() {
console.log("Button clicked");
}
publicMethod() {
// 在公共方法中调用按钮的函数
this.buttonClick();
}
}
使用ViewChild装饰器获取到按钮的引用,然后在公共方法中,调用按钮的函数。
HTML模板:
组件类:
import { Component, ViewChild, ElementRef } from '@angular/core';
export class AppComponent {
@ViewChild('myButton') myButton: ElementRef;
buttonClick() {
console.log("Button clicked");
}
publicMethod() {
// 在公共方法中调用按钮的函数
this.myButton.nativeElement.click();
}
}
这两种方法都可以在公共方法中调用按钮上的函数。选择哪种方法取决于你的具体需求和项目架构。