Reputation: 283
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 ?
Upvotes: 5
Views: 10688
Reputation: 179
This piece of code is working for me! You can try by your side!
component.ts ..
//new method:
callAction(actionName: string) {
return this[actionName]();
}
//example:
close() {
this.dialogRef.close();
}
component.html
<button (click)="callAction(action.method)" >
{{ action.text }}
</button>
Upvotes: 0
Reputation: 86740
You can pass varibale as method name using bracket notation like this-
<a (click)="this[action]()">
Login
</a>
(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 !');
}
Upvotes: 8
Reputation: 1847
you can probably pass a function variable if you want it to be dynamic:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
clickHandler: any;
constructor() { }
ngOnInit() {
this.clickHandler = this.funcA;
}
private funcA() {
console.log('call function A');
this.clickHandler = this.funcB;
}
private funcB() {
console.log('call function B');
this.clickHandler = this.funcA;
}
}
Upvotes: 0
Reputation: 891
This is not possible because (click) expects function to be passed, the best you can do is this:
<a (click)="action()">
Login
</a>
you need to CALL that 'action' variable that you set with function! And you cannot set action variable with string like you did! You must do it like this:
action = login();
not like this:
action = 'login()'
Hope it helps!
Upvotes: 0
Reputation: 2166
It is as simple as yours HTML:
<a (click)="login()">
Login
</a>
TS:
login() {
console.log('login !');
}
This will work for sure!
Upvotes: -3
Reputation: 416
You do not pass a vaiable.
(click)
is the event. "login()"
is the method.
To pass a variable to a function:
(click)="login(args)"
Upvotes: 4