Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular click used with a variable

Tags:

angular

I try to call (click) event in angular by passing a variable, but nothing happen

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

And in my .ts file

action = 'login()';

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

Is there a way to use (click) with a variable and not a static function name ?

like image 261
user7867717 Avatar asked May 09 '18 09:05

user7867717


2 Answers

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

like image 82
Pardeep Jain Avatar answered Oct 17 '22 22:10

Pardeep Jain


You do not pass a vaiable.

(click) is the event. "login()" is the method.

To pass a variable to a function:

(click)="login(args)"
like image 4
Daddelbob Avatar answered Oct 17 '22 21:10

Daddelbob