Home > Back-end >  How to pass data from identical multiple child component to parent in angular?
How to pass data from identical multiple child component to parent in angular?

Time:03-26

I would like to pass data from multiple identical child components to parent component. How can I achieve it. Scenario is I have a date picker and I looped the child components in parent component. So when I select date in all the child elements how can I retrieve the dates in parent component where I am having my business logic to make a service call. Thanks in advance.

CodePudding user response:

You can keep an array for all the children and their respective values in the parent component. Whenever the date value is changed in the child component, use an event emitter to pass that value to the parent. See the example below:

Child.component.ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss'],
})
export class ChildComponent {
  @Input() data: any;
  @Output('selectionChanged') eventEmitter: EventEmitter<any> =
    new EventEmitter<any>();
  constructor() {}

  onDateSelection(event: any) {
    const dateStr = event.target.value; //Pick date value
    this.eventEmitter.emit({ id: this.data.id, date: dateStr });
  }
}

Child.component.html

<p>id: {{ data.id }}</p>
<input type="date" (change)="onDateSelection($event)" />

App.component.ts (In your case this will be parent component)

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
  title = 'so-demo';
  children: any[];
  constructor() {
    this.children = [{ id: 1 }, { id: 2 }, { id: 3 }];
  }
  ngOnInit() {}

  dateSelectionChanged(data: any) {
    const { id, date } = data;
    this.children[id - 1].date = date;
    // Call your service here, I'm just gonna write to console
    console.log(this.children);
  }
}

App.component.html

<p>Hola! Select a few of below dates:</p>
<ng-container *ngFor="let c of children">
  <app-child
    [data]="c"
    (selectionChanged)="dateSelectionChanged($event)"
  ></app-child>
</ng-container>

CodePudding user response:

You can talk to a parent component by creating a provider that references the current component. Any child will then have access to that parent. See the full code on Stackblitz.com.

First step is to create a token that can be provided to your parent and injected into your children:

export const PARENT_COMPONENT = new InjectionToken<ParentComponent>('ParentToken');

Next in your parent component add a provider that references itself:

@Component({
  providers: [
    {
      provide: PARENT_COMPONENT,
      useExisting: forwardRef(() => ParentComponent),
    },
  ],
})
export class ParentComponent {}

Then in your children, inject the parent:

export class ChildComponent {
  constructor(
    @Inject(PARENT_COMPONENT) private readonly parent: ParentComponent
  ) {}
}

Now the child has access to all the parents functions, and it doesn't matter how deep the child is within the component, it could be a child or even a grand grand child (or deeper).

  • Related