首页 > 解决方案 > 与变量一起使用的角度点击

问题描述

我尝试(click)通过传递变量以角度调用事件,但没有任何反应

<a (click)="action">
  Login
</a>

在我的 .ts 文件中

action = 'login()';

login() {
  console.log('login !');
}

有没有办法使用(click)变量而不是静态函数名?

标签: angular

解决方案


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


推荐阅读