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
JavaScript
x
2
1
this.consultList;
2
parentComponent.ts
JavaScript
1
8
1
export class ParentComponent implements OnInit {
2
3
@Input() consultList: any[] = [];
4
5
testCall() {
6
console.log('Test Consult: ', this.consultList;
7
}
8
Advertisement
Answer
Here is an example stackblitz project to test parent-child data transfer, using @Input()
and @Output()
mechanism
JavaScript
1
25
25
1
import { Component, EventEmitter, Input, Output } from '@angular/core';
2
3
@Component({
4
selector: 'child',
5
template: `
6
<h1>Hello {{ name }}! This is child component</h1>
7
<button (click)="sendEventToParent()">Send data to parent</button>
8
`,
9
styles: [
10
`
11
h1 {
12
font-family: Lato;
13
}
14
`
15
]
16
})
17
export class ChildComponent {
18
@Input() name: string;
19
@Output() eventFromChild: EventEmitter<string> = new EventEmitter();
20
21
sendEventToParent(): void {
22
this.eventFromChild.emit('data from child');
23
}
24
}
25
here is the parent component html called child
JavaScript
1
5
1
<child name="{{ name }}" (eventFromChild)="onEvent($event)"></child>
2
3
<h1>This is parent component</h1>
4
<p>{{dataFromChild}}</p>
5
and event bindin like that
JavaScript
1
16
16
1
import { Component, VERSION } from '@angular/core';
2
3
@Component({
4
selector: 'my-app',
5
templateUrl: './app.component.html',
6
styleUrls: ['./app.component.css']
7
})
8
export class AppComponent {
9
name = 'Angular ' + VERSION.major;
10
dataFromChild = '';
11
12
onEvent(event): void {
13
this.dataFromChild = event;
14
}
15
}
16