I have a unique situation where I need to switch between two functions within an object literal. One function takes two numerical arguments, "A" and "B", while the other function only takes a single string argument, "C".
My TypeScript code showcases my dilemma:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Angular';
result: string = null;
v: number = 1;
firstFn(a: number, b: number) {
console.log(1);
if (a == undefined && b == undefined) return 'missingParam';
return a == b ? 'Equal' : 'Not';
}
secondFn(c: string) {
console.log(2);
return c ? c : 'noParam';
}
doStuff() {
const options = {
0: this.firstFn.apply(this, [1, 1]),
1: this.secondFn.apply(this, ['k']),
};
this.result = options[this.v];
//Toggle between the two functions
this.v == 1 ? this.v-- : this.v++;
}
}
In my HTML code, I utilize a button trigger to execute the 'doStuff()' function.
<button (click)="doStuff()">Do stuff</button>
{{ result }}
If you want to take a look at my implementation on StackBlitz, check it out here: https://stackblitz.com/edit/angular-9-starter-kq1nrx
An issue I currently face is that both the functions inside the object are being executed when I call 'doStuff()', instead of just the selected one. You can observe this in the stackblitz console.
Do you have any suggestions on how I can prevent this double function call?