Invoke a function within an Angular component that is passed in as a parameter

Is it possible to invoke a function using a string in JavaScript?

I have a scenario where I receive a string as the function name, and I need to call and run that function. However, my current code is not working as expected.

Below is the code snippet I tried:

 linkAction(attr,url){
      if(attr == 'click'){
        debugger
        let eventName = Object.keys(url)[0];
        this[eventName];
      }else{
        window.open(url, "_blank");
      }
    }

Unfortunately, this code does not successfully call the method as intended.

Answer №1

See the Demo

Here is an example of how you can implement this:

.html

<button (click)="linkAction('click', 'test')">Click me </button>
<button (click)="linkAction('url', 'www.example.com')">Click me URL </button>

.ts

  linkAction(attr, item) {
    if (attr == "click") {
      this[item]();
    } else {
      if (item !== "" && item !== undefined) {
        if (item.includes("http")) {
          window.open(item, "_blank");
        } else {
          window.open(`https://${item}`, "_blank");
        }
      }
    }
  }

  test() {
    alert("test function called");
  }

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

The functionality to generate personalized worldwide timezone pipe is not functioning

I'm completely new to Angular and I've been working on creating a custom pipe for adjusting timezones. The idea is to allow users to select their preferred timezone and have the offset applied accordingly. To start, I created a file called timez ...

Utilizing history in React with Typescript: A step-by-step guide

I am currently working on a function that navigates to My Page upon clicking a button. However, I encountered an error when trying to implement it in Typescript instead of JavaScript. I am seeking assistance to resolve this issue. //Topbar.tsx function Top ...

Troubleshooting the error message "Encountering issues with Module build failed (from ./node_modules/postcss-loader/src/index.js)"

Running ng serve results in compilation failure after the chunks are generated. The same codebase is functioning on a co-worker's computer with identical versions as listed below: Node version: 10.16.3 NPM version: 6.9.0 @angular/cli: 7.3.9 Tried ...

Tips for validating the request body prior to sending in Angular unit testing

I'm experiencing some difficulties creating a unit test. Despite reading numerous articles, none have proven to be helpful in simplifying the process. The specific function I need to test returns an Observable. My main objective is to ensure that myB ...

Ways to initiate a fresh API request while utilizing httpClient and shareReplay

I have implemented a configuration to share the replay of my httpClient request among multiple components. Here is the setup: apicaller.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http& ...

The use of props within components is broken in the interface of Nuxt and Vuejs

I am having trouble accessing an object's interface within a component using props. Is there anyone who can provide guidance on how to resolve this issue? PortariaInterface define interface PortariaInterface { entryDate: string nfe?: { numbe ...

Error thrown by webpack: Module 'pug' not found when attempting to access get-api

After setting up webpack in express, a new folder was created. When I try to run bundle.js, it shows the message "server is running on port 3000". However, when I access the API at http://localhost:3000/api/test, the whole bundle.js loads in the console an ...

TypeError: describe is not a function in the Mocha testing framework

Encountering an issue with mocha-typescript throwing an error indicating that describe is not defined. TypeError: mocha_typescript_1.describe is not a function at DatabaseTest.WrongPath (test/database_test.ts:21:9) at Context.<anonymous> ...

Are there any potential risks in sticking with Angular 2 instead of upgrading to a newer version?

Our current legacy app has been utilizing Angular 2.4 from the start. The package.json file contains numerous overrides for packages, leading us to use npm install --force during our build process due to peer dependency conflicts and unresolved dependencie ...

Creating a hierarchical visualization in Angular using a JSON object array

I'm currently working on creating a hierarchical view of users. My ultimate goal is to utilize this hierarchy view or something similar. The challenge lies in how the JSON objects used to construct the hierarchy are structured. Here's an example ...

Unlocking the Secrets of Passing ID Parameters Between Pages and Fetching Data from External APIs in Ionic 4

Before I get into it, apologies for the basic question, but I'm struggling to figure this out. Here's my issue: I have a list of categories that are being fetched from a nodeJS api. My goal is to fetch the subcategories based on the id from the d ...

Replacing a component dynamically within another component in Angular 2

I am currently working on integrating a component within another component that has its own view. The component being loaded will be determined dynamically based on specific conditions. Essentially, I am looking to replace one component with another compo ...

Reacting to Appwrite events in a React Native environment

My React Native application encounters an error when subscribing to realtime events. The error message reads as follows: ERROR Error: URLSearchParams.set is not implemented, js engine: hermes. appwriteClient .subscribe( `databases.${APPWRITE_DATAB ...

Have you considered using Compodoc for documenting Storybook components?

While setting up an Angular Storybook project, we are prompted to integrate Compodoc for documentation purposes. I am curious to know if Compodoc offers additional features to Storybook or is it simply a different method of presenting documentation? ...

In Vue using Typescript, how would I go about defining a local data property that utilizes a prop as its initial value?

When passing a prop to a child component in Vue, the documentation states: The parent component updates will refresh all props in the child component with the latest value. Avoid mutating a prop inside a child component as Vue will warn you in the consol ...

How can you add or remove an item from an array of objects in Angular/RXJS using Observables?

Purpose: The goal is to append a new object to an existing Observable array of objects and ensure that this change is visible on the DOM as the final step. NewObject.ts: export class NewObject { name: string; title: string; } Here's the example ...

Webpack, TypeScript, and modules are set to "esnext," resulting in a change to undefined

In my setup, I am using webpack with typescript (via ts-loader). To enable code splitting in webpack, it is necessary to adjust the module setting to esnext in the tsconfig file: // tsconfig.json { "compilerOptions": { "module": ...

Issue with Angular 2: MaterializeCSS module not loading correctly when using routing

I am currently incorporating MaterializeCSS into my Angular project. It appears that materialisecc.js and/or jquery.js are loaded with routing, causing the need to reload each page of the app for it to function properly. This issue is affecting the overall ...

The use of findDOMNode has been marked as outdated in StrictMode. Specifically, findDOMNode was utilized with an instance of Transition (generated by MUI Backdrop) that is contained

I encountered the following alert: Alert: detectDOMNode is now outdated in StrictMode. detectDOMNode was given an instance of Transition which resides within StrictMode. Instead, attach a ref directly to the element you wish to reference. Get more inform ...

What steps can be taken to retrieve error.data from RTK Query while utilizing typescript?

When I log error to the console, this is what I see: { status: 401, data: "Invalid password" } If I attempt to log error.data, an error occurs: The "data" property does not exist in the "FetchBaseQueryError|SerializedErr ...