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; }
Advertisement
Answer
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; } }