Trigger a child component function in Angular by responding to user input

Within my application, there exists a parent component (pc) along with 4 child components (cc1, cc2, cc3, and cc4). Imagine a situation where a user inputs a number between 1-4 into a text field, and I want to call a specific function in the corresponding child component.

For instance, if I wanted to execute a function from child component 2, I could use @ViewChild:

@ViewChild('cc2') child;

and then invoke the function using:

this.child.somefunc();

However, it is not possible to achieve something like this:

@ViewChild('cc' + ValuefromUser)

during an onClick event, for instance, to obtain a reference to the desired component. Do you have any suggestions on how I can accomplish this?

Answer №1

One way to access them is by using the ViewChild decorator and assigning them to different variables:

@ViewChild('cc1') child1;
@ViewChild('cc2') child2;
...

In this scenario, you can reference template elements either by their template variable name (e.g. cc1) or by their component class (e.g. Child1Component).

Another approach is to fetch them with the ViewChildren decorator into a single variable:

@ViewChildren('cc1, cc2, cc3, cc4') children;

In this case, you can only refer to the template elements by their template variable name. It may be challenging to distinguish between them since the children variable stores instances of component classes. You would need to compare them against a map of classes to filter out those with the desired identifier using QueryList methods such as filter or find:

const childrenMap = { 1: Child1Component1, 2: ... };

...

const filteredChildren = children.filter(child => {
  if (childrenMap[valuefromUser])
    return filteredChild instanceof childrenMap[valuefromUser]);
});

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

retrieving JSON data within the controller

When I use the command console.log($scope.data), I am able to view my JSON file. Additionally, by using <div ng-repeat="item in data">, I can see all the items in the view. However, when I try console.log($scope.data[0]) or console.log($scope.data[0] ...

Accessing FUSEKI using JavaScript

I'm new to working with SPARQL queries in JavaScript and I need some guidance on how to send these queries to FUSEKI. I am having trouble figuring out if this is even possible and, if it is, what the correct method is. Currently, I am attempting to u ...

What is the best way to change between different Angular 2 material tabs using typescript?

I need help with switching tabs using buttons <md-tab-group> <md-tab label="Tab 1">Content 1</md-tab> <md-tab label="Tab 2">Content 2</md-tab> </md-tab-group> <button md-button (click)="showTab1()">Show Tab 1< ...

Preparing data in the Vuex Store efficiently for an AJAX request

Dealing with a Vuex store that holds around 30 fields has been quite the challenge for me over the past couple of days. I've been struggling to properly gather the data before sending it through an AJAX post method. Being aware of the reactivity of Vu ...

Initiate the Brave web browser on a Linux system with the help of selenium and JavaScript

Attempting to set up a simple hello world app for learning Selenium. My goal is to create a script that launches the Brave web browser. After trying various code snippets from online sources and Stack Overflow, none of them seem to work as expected. const ...

The implementation of user context failed to meet expectations in terms of writing

I need some clarification regarding userContext in react with typescript. Initially, I define it in RubroContext.tsx import { createContext, useContext } from "react"; import { RubroType1, RubroType2 } from "../Interfaces/interfaces"; ...

Getting the component class from a native element reference in Angular: A step-by-step guide

I have an HTML Div element with angular component children inside the div. Somehow the angular template is like this. <mat-radio-group [(ngModel)]="selectedRadioValue"> <div #radioButtonDiv *ngFo ...

Getting an error with TypeScript and React refs: Cannot access property 'current' when it's undefined

I am currently developing a React application using TypeScript. One of the features I want to implement is a button that scrolls to a specific header in a child component on the main page. To achieve this, I have created a reference in the child componen ...

Leveraging the result of one ajax function within a different ajax function

My current project involves the following steps: 1. User creates a template with various elements. 2. When the user clicks a button: *The first ajax function establishes a new entry in the custom template database. *The second ajax function retrieves the ...

Utilize Typescript to ensure uniformity in object structure across two choices

Looking to create a tab component that can display tabs either with icons or plain text. Instead of passing in the variant, I am considering using Typescript to verify if any of the icons have an attribute called iconName. If one icon has it, then all othe ...

Integrate a dynamic component into the Angular 7 template

The code I am working with currently has a scenario where during the ngOnInit() execution, the correct component is stored in this.widget, along with appropriate data in this.data. I encountered difficulty trying to smoothly integrate the dynamic componen ...

What are some ways to reinvigorate your determination?

With the use of ui-router, a state is created with a resolve function: .state('tab.social', { url: '/social/', views: { 'menuContent': { templateUrl: 'templates/social/tab-social.html', ...

A guide on incorporating typings for d3-tip in TypeScript 2.0

Seeking to implement tooltips in my charts using the d3-tip library. After installing typings for d3-tip in Typescript 2.0: npm install @types/d3-tip --save The typings appear in my package.json: "dependencies": { "@types/d3": "^4.7.0", "@types/d3- ...

The alterations made to a single dropdown option are causing ripple effects across all other dropdowns

There is an add button that continuously adds a div container containing two dropdowns. The selection in one dropdown affects the data in the other dropdown. When the add button is clicked, a second div with both dropdowns is added. However, changing the ...

Does implementing HTTPS on my web server also secure my AJAX calls?

Picture a scenario where I have a compact webpage that I access via https, which has a valid certificate and loads data through an ajax call as shown below: $.ajax( { type:"POST", url:"ressource/js/load_footer.php", data:"page= ...

Toggle the play/pause function by clicking - Trigger Ajax

I have a campaign that can be either played or paused. Currently, I have implemented the pause feature using AJAX and now I need to add the play feature as well. When I click on the pause button, I want it to be replaced with the play button. This is the ...

"Explore a different approach to file uploading with React Native JavaScript by using either blob or base64 encoding

I am in the process of uploading visuals. When I employ this technique, it functions as expected: formData.append("file",{uri,type,name}); Yet, I prefer not to transmit my visual using the URI. My intention is to divide the visual into distinct sections ...

Exploring the Angular way of searching through arrays of objects

What is the most efficient method for searching a specific parameter within an object array in Angular? I am populating my array using Angular's foreach method: $scope.arrayiwanttosearch = []; angular.forEach(data, function(value, key) { ...

Finding the Port Number where the NodeJS server is actively listening

I am currently facing an issue retrieving the port number on which NodeJS is listening. I have saved the port number value in the app.js variable and attempted to access it in the index.js file. However, I keep getting an undefined value in the index.js fi ...

Creating a Custom Emoji Module

Currently working on creating an emoji component using JavaScript without the React framework. Does anyone know of a comprehensive list containing the unicodes for all emojis? I can successfully display an emoji on the screen by using its Unicode (e.g. & ...