Tips for Simplifying Complex Switch Cases with Object Literals in TypeScript

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?

Answer №1

The best solution is to swap out .apply() for .bind(). By using bind, the function is not immediately called, preventing the output of two logs.

Furthermore, remember that you must now call the function when obtaining the reference:

this.result = opt[this.v]();

Here's the revised code:


  doSomething() {
    const options = {
      0: this.firstAction.bind(this, [1, 1]),
      1: this.secondAction.bind(this, ['k']),
    };

    this.result = options[this.v]();

    //Switch between the two actions
    this.v === 1 ? this.v-- : this.v++;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an error while attempting to use the 'setAttribute' method on the 'Element' object: ']' is not a recognized attribute name. This issue arose within an Angular 4 project

I encountered the following issue: Failed to execute 'setAttribute' on 'Element': ']' is not a valid attribute name. I defined a model as follows: export interface ModalComponentModel { username: string; password: s ...

Converting an array of arrays into an object with an index signature: A step-by-step guide

I find myself facing a challenge where I have two types, B and A, along with an array called "a". My objective is to convert this array into type B. Type A = Array<[string, number, string]>; Type B = { [name: string]: { name: ...

Whenever I try to run npm start within my angular component, I encounter a compilation problem

I am currently working on dynamically rendering a component on one of my screens. To achieve this, I am utilizing the componentFactoryResolver.resolveComponentFactory and viewContainerRef.createComponent APIs. I have declared the variable "loadedComp : Glo ...

There seems to be an issue in Angular as it is unable to retrieve /

I'm encountering an issue with my simple application where I am receiving the error message "Cannot GET /." Also, in the console, I see this error: TypeError: Cannot read property 'checked' of null at Object.SL_BBL_locer. I'm unsure ab ...

Developing Angular2 applications in Visual Studio Team Services (formerly known as Visual Studio Online)

Currently, I have an angular2 client integrated into a Visual Studio vNext (ASP.Net 5) project. During my attempt to create a build in Visual Studio Team Services, I encountered errors similar to this one during the build step: It appears that module &a ...

Analyze the information presented in an HTML table and determine the correct response in a Q&A quiz application

I need to compare each row with a specific row and highlight the border accordingly: <table *ngFor="let Question from Questions| paginate: { itemsPerPage: 1, currentPage: p }"> <tr><td>emp.question</td></tr> <tr> ...

Clicking on the button in Angular 2+ component 1 will open and display component 2

I've been developing a Angular 4 application with a unique layout consisting of a left panel and a right panel. In addition to these panels, there are 2 other components within the application. The left panel component is equipped with buttons while ...

I'm getting errors from TypeScript when trying to use pnpm - what's going

I've been facing an issue while attempting to transition from yarn to pnpm. I haven't experimented with changing the hoisting settings yet, as I'd prefer not to do so if possible. The problem lies in my lack of understanding about why this m ...

Troubleshooting the ngx-image-zoom dependency error: How to resolve the unresolved dependency issue

When working on an angular project in version 10, I encountered challenges while installing the ngx-image-zoom component due to dependencies with angular 10. Despite this, I managed to resolve the issues. However, in my current project using angular 11, I ...

Why isn't Nodemon monitoring the directory in webpack-typescript-node.js?

Here are the contents of the package.json file for a TypeScript project using webpack and node.js: "scripts": { "build": "webpack", "dev:start": "nodemon --watch src --exec \"node -r dotenv/co ...

Having trouble showing table data in Angular

My goal is to showcase data from a table created using Spring-Boot Below is my model.ts: export class Quiz1 { QuestionId?: any; Question?: string; OptionsA?: string; OptionsB?: string; OptionsC?: string; OptionsD?: string;} He ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

Utilizing React with Typescript: A guide to working with Context

I have a super easy app snippet like import React, { createContext } from 'react'; import { render } from 'react-dom'; import './style.css'; interface IAppContext { name: string; age: number; country: string; } const A ...

After successfully building with Vite, an error occurs stating "TypeError: can't convert undefined to object." However, during development with Vite, everything functions flawlessly

Currently, I am utilizing Vite in conjunction with React and Typescript for my project. Interestingly, when I execute 'vite dev', the live version of the website works flawlessly without any errors showing up on the console. However, things take ...

What is the method for declaring personalized environment variables in Angular?

I am looking to utilize a different environment variable called test. The purpose behind this is to set up an http interceptor for my integration tests. This interceptor should specifically return a mocked response with predefined data and is intended for ...

Utilizing Ace with a personalized theme in Angular 2 application while straying away from the default theme directory

I am currently facing an issue with integrating an Ace editor into my Angular 2 application, which is built using angular-cli. I want to link the Ace editor to a custom theme stored in the app's assets folder src/app/assets instead of within node_modu ...

Too many open files error encountered in Watchpack (watcher) - NextJS

Encountering an issue with watchpack resulting in the error messages shown above while running a next app using next dev. The error message is displayed continuously on the screen as follows: Watchpack Error (watcher): Error: EMFILE: too many open files, w ...

Angular 2: Streamlining user interface connections with extensive data rows

My challenge lies in displaying a list of items stored in an array[] when the user clicks on a tab. The data set contains around 10k rows, which is quite large, and currently takes approximately 2 to 3 seconds to render on the UI after the click event. I a ...

Is there a way to reverse the direction of the slider's track?

Our goal in the design is for users to select a value between 0 and 20, with the selected range being that value up to 20. Currently, Angular Material slider component highlights values from 0 up to the selected value as the active track. Is there a way to ...

Checking the formik field with an array of objects through Yup for validation

Here is a snippet of the code I'm working on: https://codesandbox.io/s/busy-bose-4qhoh?file=/src/App.tsx I am currently in the process of creating a form that will accept an array of objects called Criterion, which are of a specific type: export inte ...