Is it achievable to have a Dynamic Angular Output?

With multiple parent components needing a common child component that can dynamically and automatically adapt to each case, I am faced with the challenge of generating buttons using a forEach loop with data provided by the parent component (such as name, CSS class, and output name).

My main question is: Is it possible to dynamically create Outputs that directly link to the corresponding parent function?

One potential solution I have considered is to have a single output that sends a string or always integrates with the same parent function, which would then interpret and redirect it to the appropriate function using a switch statement. However, this approach doesn't seem very elegant or efficient to me.

So far, I have attempted to implement this in the child component, but I encountered an error in the editor:

child-component.components.ts

@Input() myButtons: any[];
constructor() {
    this.myButtons.forEach(array => {
      @Output() array.variableName: EventEmitter<number>;
    });
}

Of course, I am sending an array with all the necessary data from the parent:

parent-component.components.html

<app-child-component [myButtons]="buttonsArray"></app-child-component>

Answer №1

After seeking assistance from the community at "Stack Overflow en Español", also known as Stack Overflow in Spanish, I was able to find the solution I was looking for.

1- I discovered that Dynamic Output cannot be utilized due to the fact that the annotations/decorations 'Input' and 'Output' are applied during compile time and not at runtime.

These annotations do not exist in JavaScript and are used to enhance functionality during compile time, making it impossible to dynamically modify the code during runtime.

2- An alternative approach is to use event handlers:

In this method, the parent component can include a function within the data provided to the child component, which will be triggered in response to an event on the element being created.

For instance, an array of data objects is created with properties such as eventHandler and text.

The child component then receives this array and generates a series of buttons. When a button is clicked, the function specified in the eventHandler property is executed.

Parent Component

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {

  data = [
    {
      eventHandler: () => {
        alert("button 1");
      },
      text: "button 1"
    },
    {
      eventHandler: () => {
        alert("button 2");
      },
      text: "button 2"
    }
  ];
  
}

Child Component

import { Component, Input } from "@angular/core";

@Component({
  selector: "hello",
  template: `
    <div *ngFor="let d of data">
      <button (click)="d.eventHandler()">{{ d.text }}</button>
    </div>
  `,
  styles: [
    `
      h1 {
        font-family: Lato;
      }
    `
  ]
})
export class HelloComponent {
  @Input() data: any[];
}

View Live Demo

Link to the original question in Spanish

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

Executing a service request in Angular 2 using a versatile function

I have a function that determines which service to call and a function template for calling the service returned by that function. This function makes HTTP requests using http.get/http.post, which return an Observable and then perform a map operation on th ...

Generate types based on properties of a nested interface dynamically

Consider the setup provided: enum FormGroups { customer = 'customer', address = 'address', } interface Customer { 'firstName': string; } interface Address { 'street': string; } interface SomeFormEvent { ...

Error message: Unable to instantiate cp in Angular 17 application while building with npm run in docker container

After creating a Dockerfile to containerize my application, I encountered an issue. When I set ng serve as the entrypoint in the Dockerfile, everything works fine. However, the problem arises when I try to execute npm run build. Below is the content of my ...

A guide to implementing Typescript Generics in modifier functions

I am searching for a solution to properly enforce strong typing in the following scenario. I believe Typescript Generics might be the way to go here. interface Person { name: string; age: number; } const person: Person = { name: "John", ...

The `@ViewChild` reference cannot be found

My main challenge is toggling a @ViewChild element using an *ngIf, followed by invoking a native event. This snippet shows my HTML element, tagged with #audioPlayer for extracting it through @ViewChild. <audio #audioPlayer *ngIf="convers ...

What is the method for dynamically assigning a name to ngModel?

I have the following code snippet: vmarray[]={'Code','Name','Place','City'} export class VMDetail { lstrData1:string; lstrData2:string; lstrData3:string; lstrData4:string; lstrData5:string; ...

What is preventing me from assigning to a class variable within a $http success handler?

During the course of my project, I have encountered a perplexing situation that is difficult to comprehend. My intuition tells me that the issue lies in a peculiar nuance of javascript while I am working in TypeScript. Unfortunately, I am unable to prove t ...

Guide on launching a bootstrap modal using ngIf

Hello everyone, I appreciate your patience as I am new to this! Currently, I am attempting to activate a Bootstrap modal using an ngIf condition. Specifically, the goal is for the modal to open when there is existing artwork present and allow for the addit ...

The FaceBook SDK in React Native is providing an incorrect signature when trying to retrieve a token for iOS

After successfully implementing the latest Facebook SDK react-native-fbsdk-next for Android, I am facing issues with its functionality on IOS. I have managed to obtain a token, but when attempting to use it to fetch pages, I keep getting a "wrong signature ...

If an interface property is set as (), what significance does it hold?

While exploring the Vue.js source code located at packages/reactivity/src/effects.ts, I came across this snippet: export interface ReactiveEffectRunner<T = any> { (): T effect: ReactiveEffect } I'm curious, what does () signify in the code ...

Add a hash to the file name of the JSON translation asset

To prevent caching issues, I choose to store my translation files as JSON in /src/assets/i18n. To achieve this in Angular, I am looking for a way to add a unique fingerprint or hash to the filename of the file and use that hashed name when retrieving the ...

Tips for converting string values from an Observable to numbers using the parseFloat() method

Having trouble converting text to numbers for geolocation coordinates. My model consists of a site with an ID and an array of points as a property. Rather than creating a relationship between site and points, I've structured it differently. In my cod ...

Angular application encountering a 401 unauthorized error when attempting to connect to TFS API

Having trouble with an API get request in my initial Angular project. I'm attempting to retrieve all projects from a server using the correct URL (which works in Postman and my browser), as well as a token generated from my TFS account. Despite this, ...

The specified React element type is not valid

Currently working on a web application using Typescript, Electron, Webpack, and NodeJS, but encountering issues with the import/export functionality. The error message that I am facing reads: "Warning: React.createElement: type is invalid -- expect ...

Error in the design of PrimeNg calendar rendering in Angular 2

I have implemented the primeNg module from primefaces in Angular 2 to create a timepicker. It seems to be working, but the design appears broken. Is there something else I need to add to correct the design? Below are the versions of the packages I used: P ...

Create a reusable React component in Typescript that can handle and display different types of data within the same

I have a requirement to display four different charts with varying data types. For instance, interface dataA{ name: string, amount: number } interface dataB{ title: string, amount: number } interface dataC{ author: string, amount: ...

Saving the compiled Angular dist folder in the artifactory repository

Our team utilizes Artifactory to manage libraries and artifacts. We have configured the npm registry to point to our Artifactory URL for library retrieval. GitLab is integrated into our CI pipeline. Specifically, I have implemented a job that compiles the ...

Sorting List Algorithm

Looking to create an algorithm in Node.js that abides by specific rules. It takes a series of numbers as input and the maximum consecutive number before taking a break. The logic is as follows: The rules : Only one competition per day Competitions are hel ...

Retrieving and merging data from an API using Angular 6

Is it possible to retrieve data from an API and gather each user's posts along with their comments in a single JSON object? To fetch posts, you can utilize the following API: https://jsonplaceholder.typicode.com/posts As for retrieving comments, you ...

Rendering illuminated component with continuous asynchronous updates

My task involves displaying a list of items using lit components. Each item in the list consists of a known name and an asynchronously fetched value. Situation Overview: A generic component named simple-list is required to render any pairs of name and va ...