angular - 与变量一起使用的角度点击
问题描述
我尝试(click)
通过传递变量以角度调用事件,但没有任何反应
<a (click)="action">
Login
</a>
在我的 .ts 文件中
action = 'login()';
login() {
console.log('login !');
}
有没有办法使用(click)
变量而不是静态函数名?
解决方案
First Method -
You can pass varibale as method name using bracket notation like this-
<a (click)="this[action]()">
Login
</a>
Working example
Second Method -
(click)
event always expects functionName()
as it's value.
In your scenario you can add dynamic eventListner
to listen to your function using @viewChild
like this -
<a #myEvent (click)="action">
Login
</a>
@ViewChild('myEvent') myEvent: ElementRef;
ngAfterViewInit() {
(this.myEvent.nativeElement as HTMLElement).addEventListener('click', this.login.bind(this));
// Here you can bind to any method
}
login() {
console.log('login !');
}
Working example
推荐阅读
- laravel - Laravel 回显服务器无法启动
- javascript - 传递给 Illuminate\Database\Eloquent\Builder::create() 的参数 1 必须是数组类型,给定 null .. 发布数据时出错
- python - 如何从嵌套列表中提取具有最低整数值的子列表?
- java - 将 Java-8 流结果拆分为成功和失败列表
- react-native - 当数据是来自使用本机反应的 api 的动态数据时,自动图像轮播的问题
- python - Pytorch:沿多个轴的张量索引或一次分散到多个索引
- jenkins - Transifex 推送突然失败?
- elixir - 添加对现有列和表的引用
- docker - 如何在 docker 的特定文件夹中运行 jupyter notebook
- .net - 将 AWS lambda 项目中添加的公共方法公开为 api