Using ngFor to dynamically call functions

In my code, I have an array called 'actionsArray' which contains objects of type 'Action'. Each Action object has two parameters: the function name and a boolean value (which is currently not important).

let actionsArray: Action[] = [{name:"save",enabled:true},{name:"describe",enabled:true},{name:"delete",enabled:true}]

To display a list of functions using ngFor, I want to dynamically bind the "click" event of each Action to its corresponding function.

<li *ngFor="let action of actionsArray">
        <button (click)="this[action.name]()"> {{action.name}} </button>
</li>

I have tried various methods but have not been successful so far.

Answer â„–1

I implemented your code in a CodePen and it functions properly. Additionally, I incorporated an alternative switch/case method.

@Component({
  selector: 'my-app',
  template: `
    <li *ngFor="let action of actionsArray">
        <button (click) ="[action.name]()"> {{action.name}} </button>
        <button (click) ="callAction(action.name)"> {{action.name}} </button>
    </li>
  `
})
class AppComponent {  
  actionsArray: {name: string, enabled: boolean}[] = [{name:"save",enabled:true},{name:"describe",enabled:true},{name:"delete",enabled:true}]

  callAction(actionName: string) {
    switch(actionName){
      case 'save' : return this.save();
      case 'describe' : return this.describe();
      case 'delete' : return this.delete();
    }
  }

  save() {
    alert('save');
  }

  describe() {
    alert('describe');
  }

  delete() {
    alert('delete');
  }
}

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

Suggestions for enhancing or troubleshooting Typescript ts-node compilation speed?

Recently, I made the switch to TypeScript in my codebase. It consists of approximately 100k lines spread across hundreds of files. Prior to the migration, my launch time was an impressive 2 seconds when using ESLint with --fix --cache. However, after impl ...

Customizing AxiosRequestConfig with Axios in TypeScript can greatly enhance the functionality and

Currently working with React and Axios. Lately, I've been experimenting with custom configurations in Axios as shown below: import $axios from 'helpers/axiosInstance' $axios.get('/customers', { handlerEnabled: false }) However, wh ...

What is the process for inputting a predefined function into an interface?

In my project, I have a Locale interface that defines the properties of a locale for my component: interface Locale { src: string; alt: string; language: string; i18nFormat: string; } During debugging, I am using the built-in .toSource() function ...

One cannot use a type alias as the parameter type for an index signature. It is recommended to use `[key: string]:` instead

I encountered this issue in my Angular application with the following code snippet: getLocalStreams: () => { [key: Stream['key']]: Stream; }; During compilation, I received the error message: An index signature parameter typ ...

`Square payment integration using the mean stack technology stack`

Seeking advice on how to integrate Square payment form with angular and node. The form functions properly, but upon hitting send, it fails to post to /process-payment. As a newcomer to the MEAN stack, I am unsure where to start regarding using angular and ...

Having trouble navigating to a child page in Angular 4

When I try to follow the Angular routing & navigation example, I encounter an issue where my page displays as "file not found" when I route. Even when I navigate to the profile page at profile.component.html, I can see my columns, but nothing appears from ...

Executing the Ionic code within the Xcode Swift environment

I have developed an Ionic application that I successfully compiled in Xcode for iOS. Additionally, I have integrated a widget into the application. My goal is to set it up so that when the application is opened using the regular app icon, it displays the m ...

How can I implement a redirect back to the previous query page post-authentication in Next.js 13?

To enhance security, whenever a user tries to access a protected route, I plan to automatically redirect them to the login page. Once they successfully log in, they will be redirected back to the original protected route they were trying to access. When w ...

How come webstorm/react-hook-forms isn't showing me suggested choices for the "name" field?

I'm looking to create components with inputs, but I'm currently facing an issue with tooltips not showing for the name. I would like the form fields to display the name. export const Form: FormType = ({ children, form }) => ( <FormProvide ...

Working with base URL and relative paths in Angular 2 on GitHub Pages

While attempting to deploy my project site on gh-pages, I encountered an issue with relative paths in the templates of my Angular2 app that uses webpack. Despite setting the base URL to match my repository name, everything loads fine except for the paths w ...

Creating a Dynamic Download Link in Angular 6

Hello everyone, I need assistance in making my download feature dynamic. Here is my HTML code: <button class="btn btn-primary" (click)="downloadMyFile({{account.students[0].schoolId}})"><i class="fa fa-file-pdf-o"></i> Download</butt ...

The package information could not be loaded from the registry due to an error: The "timeout" parameter must be in numerical form. Instead, it was received as a string ('100000')

Encountered an issue while trying to install Angular Material in my project: PS C:\Users\Avinash Kumar\Desktop\Projects\CRUD\Project 2\Library Management System\UI\UI\Frontend> ng add @angular/material â ...

Tips on preventing duplicate class properties when they are declared separately from the constructor and then initialized

Imagine you have a simple ES6 class and you want to avoid redundancy by extracting constructor parameters into a separate type. For example: type BarParams = { x: string; y: number; z: boolean; }; export class Bar { public x: string; public y: n ...

Currently, I am utilizing version 6.10.0 of @mui/x-date-pickers. I am interested in learning how to customize the color and format of a specific component within the library

I'm currently using @mui/x-date-pickers version 6.10.0 and I need to customize the color and format for a specific section in the mobile view. How can I achieve this? I want to display the date as "May 31st" like shown in the image below. Is there a ...

Issues with Cross-Origin Resource Sharing (CORS) have been identified on the latest versions of Android in Ionic Cordova. However, this problem does not

I am encountering an issue with my TypeScript Ionic code. It works well in browsers and some older mobile devices, but it fails to function on newer Android versions like 8+. I need assistance in resolving this problem. import { Injectable } from '@an ...

Integrating a packaging NPM functionality into Angular for streamlined development

After completing a software engineering assignment, I am struggling with the final requirement. I need to implement an NPM packaging command called "npm build" to compile and publish the front end developed in Angular to the backend project. Initially, I t ...

Instructions for opening a URL in a new tab using Angular

Within my Angular 10 application, I am conducting an API call that retrieves an external URL for downloading a pdf file. Is there a method to open this URL in a new browser tab without relying on the window object? I've been using window.open(url) suc ...

Using TypeScript to declare ambient types with imported declarations

In my TypeScript project, I have a declaration file set up like this: // myapp.d.ts declare namespace MyApp { interface MyThing { prop1: string prop2: number } } It works perfectly and I can access this namespace throughout my project without ...

What is the procedure for setting up the typings folder in AngularJS 1.5 with TypeScript?

I'm currently working on a project using AngularJS 1.5 and TypeScript. I need to install the "angularjs/angular.d.ts" and "angularjs/angular-route.d.ts" files. Despite installing tsd globally, when I run the command "tsd install angular," I receive a ...

Extending Partial Interface in a Typescript Class

My goal is to create a class that inherits all the properties of an interface, without explicitly declaring those properties itself. The interface properties are added during the build process and will be available at runtime. After coming across this hel ...