Home > Enterprise >  How to pass data from child to parent?
How to pass data from child to parent?

Time:09-16

I need to pass one variable, that is inside my child component, to parent page. This variable that I am trying to pass, is the array result of Barcode Scanner.

And I need to pass it to parent to send to API.

childComponent.ts

this.consultList;

parentComponent.ts

export class ParentComponent implements OnInit {

@Input() consultList: any[] = [];

testCall() {
console.log('Test Consult: ', this.consultList; 
}

CodePudding user response:

Here is an example stackblitz project to test parent-child data transfer, using @Input() and @Output()mechanism

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

@Component({
  selector: 'child',
  template: `
    <h1>Hello {{ name }}! This is child component</h1>
    <button (click)="sendEventToParent()">Send data to parent</button>
  `,
  styles: [
    `
      h1 {
        font-family: Lato;
      }
    `
  ]
})
export class ChildComponent {
  @Input() name: string;
  @Output() eventFromChild: EventEmitter<string> = new EventEmitter();

  sendEventToParent(): void {
    this.eventFromChild.emit('data from child');
  }
}

here is the parent component html called child

<child name="{{ name }}" (eventFromChild)="onEvent($event)"></child>

<h1>This is parent component</h1>
<p>{{dataFromChild}}</p>

and event bindin like that

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular '   VERSION.major;
  dataFromChild = '';

  onEvent(event): void {
    this.dataFromChild = event;
  }
}

CodePudding user response:

What you are thinking of is called an abstract class. An abstract class can define abstract properties just like an interface, abstract methods just like an interface, and unlike an interface it can actually implement methods. You cannot initialize an abstract class, but you can inherit code for re-use from it.

https://codesandbox.io/s/patient-breeze-h4s3t?file=/src/index.ts

abstract class Parent {
  abstract someProperty: string;

  someCall() {
    console.log(this.someProperty);
  }
}

class ChildOne extends Parent {
  someProperty = "I am child one";
}

class ChildTwo extends Parent {
  someProperty = "I am child two";
}

const one = new ChildOne();
const two = new ChildTwo();

one.someCall(); // "I am child one";
two.someCall(); // "I am child two";

  • Related