Passing a variety of values from child to parent component in Angular through a unified function

Utilizing a checkbox-component within a parent component, I have implemented an @Output() to notify the parent component when the value changes.

While my code is currently functional, using the checkbox-component multiple times throughout my project has led me to avoid creating new functions each time to update variable values.

You can access my code through this link: here

I am seeking advice on how to optimize this process. Specifically, how can I eliminate the need to create a new function like onRoleChangeCheckboxX() each time a new checkbox is added. Though my stackblitz example includes just two additional functions, the concern arises when faced with having to generate 50 checkboxes.

Answer №1

It can be difficult for me to determine your exact needs, but if you're utilizing eventEmitter & Output, you have the ability to emit a complex JSON object with just one emit statement and transmit any amount of data to the parent component:

@Output() dataEvent = new EventEmitter<any>();

let jsonData = { status: 'active', quantity: 25, isEnabled: true }
this.dataEvent.emit(jsonData);

Answer №2

Perhaps this approach may not be the most optimal, but it can work in specific scenarios like this one, where there will always be a single emit handler.

  import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";
 
    @Component({

  selector: "app-checkbox",
  templateUrl: "./checkbox.component.html",
  styleUrls: ["./checkbox.component.css"]
})
export class CheckboxComponent implements OnInit {
  @Input() checkboxName;
  @Input() checkboxData:any; 
  @Input() checkBoxLinkedProp:any; // added another property it is the name of the property in the parent component you are updating 
  
  @Output() toggle: EventEmitter<any> = new EventEmitter<any>(); // emit a object instead of bool

  constructor() {}

  ngOnInit() {}

  onToggle() {
    const checkedOption = this.checkboxData;
    this.toggle.emit({checked:checkedOption , checkBoxLinkedProp: this.checkBoxLinkedProp });
  }
}

app.component.html [checkBoxLinkedProp] = "'checkbox1Value'" -- I am passing the property name as a string to the child checkbox component. And when toggled, a single method is called (toggle)="onRoleChangeCheckbox($event)"

this.toggle.emit will emit an object with the specified string prop we passed

<app-checkbox [checkboxName]='checkbox1' [checkboxData]='checkbox1Value' 
  [checkBoxLinkedProp] = "'checkbox1Value'"
 (toggle)="onRoleChangeCheckbox($event)"></app-checkbox>

<app-checkbox [checkboxName]='checkbox2' [checkboxData]='checkbox2Value'  (toggle)="onRoleChangeCheckbox($event)"
[checkBoxLinkedProp] = "'checkbox2Value'"
></app-checkbox>

app.component.ts onRoleChangeCheckbox({checkBoxLinkedProp , checked}) This method will take the property name we passed as a string from the emit event and set the state of the class accordingly.

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  checkbox1 = 'First checkbox';
  checkbox1Value = false;

  checkbox2 = 'Second checkbox';
  checkbox2Value = false;

  onRoleChangeCheckbox({checkBoxLinkedProp , checked}) {
    this[checkBoxLinkedProp] = checked; // The property name that was passed to the child is received in this emit event and set accordingly
    console.log(this.checkbox1Value , checkBoxLinkedProp); // Tested value for the first checkbox
  }

}

Answer №3

If you're looking for a solution, check out this stackblitz I created. Essentially, you just need to set up an array for your checkboxes.

  checkboxes = [
    {
      name: 'First checkbox',
      value: false
    },
    {
      name: 'Second checkbox',
      value: false
    },
  ]

By using *ngFor in your HTML, you can make it generic and easily add new checkboxes without having to modify the code directly.

<app-checkbox *ngFor="let box of checkboxes; let i = index" 
              [checkboxName]="box.name" 
              [checkboxData]="box.value"  
              (toggle)="onRoleChangeCheckbox($event, i)"></app-checkbox>

With the use of the onRoleChangeCheckbox() function, you can dynamically update your array based on the checkbox index.

  onRoleChangeCheckbox(ev, index) {
    this.checkboxes[index].value = ev;
  }

This approach will help streamline your code and eliminate repetitive tasks when adding new checkboxes to your application.

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

Using Javascript to link various arrays filled with file paths and transforming them into an object in a distinctive manner

I've tried countless times to make it work, but it just doesn't seem to work... I have an array that contains multiple other arrays: let arr = [ ["Users"], ["Users", "john"], ["Users", "john", "Desktop"], ["Users", "john", "Docum ...

Is it possible to automatically refresh the Next Auth Session upon page reloads using API data updates?

There is a scenario I'm facing where I need to ensure the Next Auth Session is updated every time the page reloads in order to reflect the latest "Users" Details. My requirement involves making an API call upon each page reload to fetch the Users dat ...

How to send form group in Angular when the enter key is pressed

When I press the submit button on a form, it sends a request to the database to filter data in a grid. However, I also want the form to submit when the enter key is pressed. HTML <form [formGroup]="bmForm" (keyup.enter)="onSearchClic ...

Tips for retrieving information from an API and displaying it in a table

I'm struggling to retrieve data (an array of objects) from an API using a Token and display them in a table using Material-UI. However, I keep encountering the following error: Uncaught (in promise) SyntaxError: Unexpected token 'A', "Access ...

Comparing the functions of useMemo and the combination of useEffect with useState

Is there a benefit in utilizing the useMemo hook instead of using a combination of useEffect and useState for a complex function call? Here are two custom hooks that seem to function similarly, with the only difference being that useMemo initially returns ...

Acquiring the class function from a service which yields a model

Within my class called userName, I have defined properties that form a model when casting from json. Additionally, this class includes a simple function that returns the full Name: export class userName { firstName: string; lastName: string; g ...

When is it necessary to use JSON.parse(JSON.stringify()) with a Buffer object?

I am currently working with Buffer objects in my existing code. let dataObject = JSON.parse(JSON.stringify(data)); At first glance, it seems like the above code is redundant and doesn't achieve much. However, replacing it with: let dataObject = data; ...

The function type '() => JSX.Element' cannot be assigned to the type 'ReactNode'

I am encountering an issue while trying to display a component using an object. The code is throwing an error: const Login = () => <>login</> const publicRoutes = [ { path: '/login', component: Login } ] function AppR ...

Adjust the ng-show attribute in a different controller

I am attempting to toggle the visibility of a div using ng-show. Specifically, I have a navbar that should only be displayed in certain views. I have one controller managing the behavior of this div, and another controller where I want to manipulate the v ...

using lodash to convert objects into arrays while maintaining parent-child relationships

Is there a way to achieve this transformation in lodash or any other JavaScript/TypeScript method? var obj = { a: [ {id:1},{id:2},{id:3}] b: [ {id:4},{id:5},{id:6}] c: [ {id:7},{id:8},{id:9}] } // Need to transform into var arr = [ {title:a ...

Master the art of seamlessly switching between multiple kendoGridDetailTemplates in the Kendo Angular DataGrid

I am working with a Kendo DataGrid and I'm looking to use it with multiple kendoGridDetailTemplate variations. Here is an example of the kendo detail grid structure: <ng-template kendoGridDetailTemplate let-dataItem > <div>{{dataIte ...

Switching from map view to satellite view on Google Maps allows you to see detailed aerial

Is there a way to switch from map view to satellite view on a Google Map using JavaScript after zooming in 100%? If so, how can it be achieved within the following JavaScript code? DEMO:http://jsfiddle.net/keL4L2h0/ // Load Google Map ///////////////// ...

Using TypeScript in React, how can I implement automation to increment a number column in a datatable?

My goal is to achieve a simple task: displaying the row numbers on a column of a Primereact DataTable component. The issue is that the only apparent way to do this involves adding a data field with indexes, which can get disorganized when sorting is appli ...

Arranging Html Bootstrap Columns in a vertical stacking layout instead of being displayed next

Hey there, I've been encountering an issue where my columns are stacking on top of each other instead of being positioned side by side. Take a look at this screenshot of my page: The content above the shopping cart should ideally be aligned to the rig ...

Adjusting the content within a text area using an AngularJS service

I am currently editing text in a textarea within the admin view and I would like to display it through an angular service on the user view. However, I want the text to be displayed in multiple rows, maintaining the same format that I entered in the textare ...

Exploring the plane intersection within a 3D object using Three.js

I attempted to create an animation using Three.js to display the intersection plane on a 3D object with the following code snippet: import React, { useRef, useEffect, useState } from 'react'; import * as THREE from 'three'; export cons ...

`Vue Router - Dynamically update route anchor on scroll`

My goal is to achieve the same routing behavior on my website as demonstrated here: https://router.vuejs.org/guide/#html. If you observe, the link changes to https://router.vuejs.org/guide/#javascript when you scroll down, and reverts when scrolling back u ...

Executing Javascript functions using a variable string name

Seeking advice on the most effective approach for calling functions with variable names that adhere to a specific rule. I am exploring alternatives to using eval() due to the numerous concerns raised about its usage online. In my current setup, each group ...

Interactive pop-up windows in Bootstrap

I encountered an issue with bootstrap modal forms where the form displays correctly after clicking on the button, but the area in which the form is displayed gets blocked! It's difficult to explain, but you can see the problem by visiting this link. ...

Whenever I try to load an image from MongoDB, I encounter the error message: "data:image/png;base64,[object Object]."

I am currently facing an issue with displaying images in an HTML table that pulls data from MongoDB. The image is not showing up, and I'm struggling to identify the root cause of the problem. Here are the steps I have taken so far: Below is the Java ...