nOp
nOp

Reputation: 301

Call a function in a child component based on an input from user in Angular

In my app, there is a parent component (pc) and 4 child components (cc1,cc2,cc3,cc4). Consider the scenario where a user enters a number between 1-4 in an input text for example, and I wish to call a function in the corresponding component.

If I wanted to call the function from child component 2, let's say, I could do it by using @ViewChild:

@ViewChild('cc2') child;

and then calling the function by :

 this.child.somefunc();

However, I can not do something like

@ViewChild('cc'+ ValuefromUser)

in an onClick event for example to get a reference to the desired component. Do you have any suggestion how can I achieve this?

Upvotes: 0

Views: 59

Answers (1)

Estus Flask
Estus Flask

Reputation: 222989

They can be queried with ViewChild to different variables:

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

In this case template element can be referred either by template variable name (e.g. cc1 string) or by component class (e.g. Child1Component).

Or they can be queried with ViewChildren to same variable:

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

In this case template elements can be referred only by template variable name. It will be harder to differentiate between them, because children contains instances of component classes, and they should be checked against a map of classes in order to filter the ones with desired identifier with QueryList filter or find:

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

...

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

Upvotes: 0

Related Questions