Sharing a function between a Parent and Child component in Angular 2

An Array named mMemberCount is present in the Parent Component. Depending on the size of this array, a child component (which is Reusable) gets attached to the Parent component.

<member-template *ngFor="let item of mMemberCount" [title]="item.relation" [memberid]="item.id" (update)="update($event)">
</member-template>

<div class="btn_container">
  <button class="button orange" type="submit">Submit</button>
</div>

The structure of the child component is as follows:

@Component({
      selector: 'member-template',
      templateUrl: './member-template.component.html',
      styleUrls: ['./member-template.component.scss'],
      providers: [],
    })

export class MemberTemplateComponent implements OnInit {

  TAG: string = " MEMBER-TEMPLATE: ";
  // Input variables are received from the parent
  @Input('title') title: string;
  @Input('memberid') memberId: number;

  @Output('update')
  datasubmit: EventEmitter<string> = new EventEmitter<string>();


  sendDataToParent(){
     let output = "Testing Eventemitter";
     this.datasubmit.emit(output);
  } 
}

The @output('update') function is functioning properly. My aim is to trigger the sendDataToParent() method of ChildComponent (MemberTemplateComponent) from the ParentComponent. In simple terms, when the user clicks the submit button in the parent component, the sendDataToParent should be executed.

Answer №1

UPDATED 11/15/17

To accomplish this task, you can utilize the @ViewChild decorator.

ParentComponent

import { AfterViewInit, ViewChild } from '@angular/core';
import { Component }                from '@angular/core';
import { MemberTemplateComponent }  from './member.template.component';

@Component({
      selector: 'parent-template',
      templateUrl: './parent-template.component.html',
      styleUrls: ['./parent-template.component.scss'],
      providers: []
})

export class ParentTemplateComponent implements OnInit {
    @ViewChild(MemberTemplateComponent) private childComponent: MemberTemplateComponent;
    ngAfterViewInit() {
         submit() {
              this.childComponent.sendDataToParent(); 
         }
    }
}

Answer №2

After much searching, I finally discovered the solution: I implemented @ViewChildren in ParentComponent

  @ViewChildren('component') components: QueryList<MemberTemplateComponent>;

Child Component-

<member-template #component *ngFor="let item of mMemberCount" [title]="item.relation" [memberid]="item.id" (update)="update($event)">
</member-template>

Loop through the Component QueryList

 this.components.forEach(component => {
      component.callChildMethod();
    });

Now parentComponent can invoke callChildMethod() on multiple child components simultaneously.

Cheers...

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

How can I access DOM elements in Angular using a function similar to the `link` function?

One way to utilize the link attribute on Angular 2 directives is by setting callbacks that can transform the DOM. A practical example of this is crafting directives for D3.js graphs, showcased in this pen: https://i.sstatic.net/8Zdta.png The link attrib ...

Why is it not possible to convert from any[] to MyType[] in TypeScript?

Within TypeScript, the any type allows for casting to and from any arbitrary type. For example, you can cast from a variable of type any to a variable of type MyArbitraryType like so: var myThing: MyArbitraryType; var anyThing: any; myThing = anyThing; / ...

What could be the reason for certain Angular modules importing successfully while others fail to do so?

I am encountering an issue with a module that I am struggling to import. Using Typescript 2.7 and Node 10 The pxl-ng-security module is showing an error in both VSCode and VS2019. When hovering over it, error 2307 is displayed. Below is the import secti ...

Determine the route parameter name based on the path string, for example, '/posts/:id'

My Route interface has a params object, and I'm looking to ensure type safety on that params object. For example: If we have a route config like this: { post: { path: 'posts/:id', } } navigate({ name: 'post', params: { wr ...

Using Typescript with Styled-Components and Styled-System: Unable to find a matching overload for this function call

Encountering the infamous "No overload matches this call" error when using a combination of Typescript, Styled-Components, and Styled-System. I've come across solutions that suggest passing a generic type/interface to the styled component, like the o ...

What is preventing TypeScript from identifying the type of a parent based on its child?

Take a moment to explore the following example: type Num = { type: 'NUMBER' numberValue: number } type Str = { type: 'STRING', stringValue: string } type B_Num = { a: Num; numberData: number; } type B_Str = { ...

Invoking event emitter within a promise in Angular 2

My event emitter is not functioning properly within a promise's then method. No errors are being generated, it just won't execute. In the child component: @Output() isLoggingIn = new EventEmitter<boolean>(); onLogin() { this.isLoggingI ...

React experimental is encountering an issue with missing property "" $fragmentRefs"" when relaying fragments

Details Recently, I decided to explore React experimental features with concurrent mode and relay. Even though I have never used relay before, I managed to make progress but ran into some issues. Initially, using the useLazyLoadQuery hook without any frag ...

Creating interfaces within props is essential for defining the structure of components

I'm trying to pass an Interface to one of my components, but I'm running into some issues with my approach. Here's what I have so far: import { InterfaceType } from "typescript"; type Props = { dataType: InterfaceType } export default ...

Utilizing React with Typescript to access specific props

I am a newcomer to React and TypeScript and I am facing a challenge while trying to enhance an existing component by creating a wrapper around it. The issue I am encountering is related to adding my custom values to the properties. My goal is to extend th ...

Creating adaptable rows and columns with Angular Material's data table feature

My approach to rendering dynamic rows and columns using a basic table was successful: <tbody> <tr *ngFor="let row of data"> <td *ngFor="let val of row"> {{ val }} </td> </tr> </tbody> </ ...

MUI provides the flexibility to adjust the opacity separately for Chip labels/icons and backgrounds

My objective is to customize the opacity of label/icon and background in MUI Chip. I want the label & icon to have an opacity of 1, while the background should have an opacity of 0.0571. Technologies used in this project include React, TypeScript, Materia ...

The .angular-cli.json file is causing issues with loading scripts

I have recently updated my .angular-cli.json file by adding new scripts in the following format: "apps": [ { "root": "src", "outDir": "dist", "assets": [ "assets", "favicon.ico" ], "index": "index.html ...

Angular's DecimalPipe will truncate any strings that exceed 10 digits

Using the decimal pipe to format numbers in an input field value| number:'0.0-6': 'en-us' When working with numbers containing more than 10 digits, it displays as follows: For 11111111111.123456, it formats to 11,111,111,111.123455 ...

Exploring ways to ensure robust typing for the body of NextApiRequest within a Next.js environment

Are you trying to figure out how to correctly define the body type of an API POST route in Next.js for better type safety? In NextApiRequest, the body is currently defined as "any" and NextApiRequest itself is not generic. I have tried forcefully assigni ...

What is the best way to verify a field against a set of string values using Typescript in a NestJS application

I currently have an Enum containing various timezones listed below export enum Timezones { 'Europe/Andorra', 'Asia/Dubai', 'Asia/Kabul', 'America/Antigua' } In the DTO file, I am attempting to valid ...

Ways to employ a Hyphen(-) to connect two strings within an ngIf condition in Angular 9

I'm dealing with an IF condition in HTML that checks for permission to access a specific page: *ngIf="permission?.product-report?.list_product_report" The name "product-report" is static and directly used in the condition. However, whe ...

Encountering an Angular error stating "RangeError: Maximum call stack size exceeded" when trying to input data

I am encountering an ERROR message in the console that says "RangeError: Maximum call stack size exceeded" when I input something into one of these fields app.component.html <div class="container-wrap"> <div class="container&qu ...

The expect.objectContaining() function in Jest does not work properly when used in expect.toHaveBeenCalled()

Currently, I am working on writing a test to validate code that interacts with AWS DynamoDB using aws-sdk. Despite following a similar scenario outlined in the official documentation (https://jestjs.io/docs/en/expect#expectobjectcontainingobject), my asser ...

Navigating the use of property annotations in Mapped Types with remapped keys

After exploring the concept of Key Remapping in TypeScript, as shown in this guide, I am wondering if there is a way to automatically inherit property annotations from the original Type? type Prefix<Type, str extends string> = { [Property in keyo ...