I tried to erase an input field from the child component, it is transferred by @Output
information that would activate a method delete()
in the parent component!
Thank you in advance
The Child can send data to Parent by raising an event, Parent can interact with the child via local variable or Parent can call @ViewChild on the child. We will look at all those options in this article. Applies to: Angular 2 to the latest edition of i.e. Angular 8.
Angular components communicate with each other to pass data. Several angular components can form a hierarchical structure, where data and events get passed in both directions. In the previous article, we learned how to pass data from parent to child components.
You could also emit an event using a shared service that has an Observable. Using RxJs, you can declare a Subject in your parent component and pass it as Observable to child component, child component just need to subscribe to this Observable. eventsSubject: Subject<void> = new Subject<void> (); emitEventToChild () { this.eventsSubject.next (); }
Use the @Input () decorator in your child component to allow the parent to bind to this input. To bind a property from parent to a child you must add in you template the binding brackets and the name of your input between them.
You can acomplish that using EventEmitter
and @Output
:
In following snippet, you can call passDataToParent()
function to pass the desired data.
child.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child-component',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
// ******** Important part ******
@Output() emitter: EventEmitter<any[]> = new EventEmitter();
dataToEmit : any = "data to pass to parent component";
constructor() {}
ngOnInit() { }
//Call this function to pass data
passDataToParent() {
this.emitter.emit(this.dataToEmit);
}
}
parent.component.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { ChildComponent } from './child-component';
@Component({
selector: 'app-parent-component',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
// ******** Get reference of child component ******
@ViewChild(ChildComponent ) child : ChildComponent ;
constructor() {}
ngOnInit() { }
receiveDataFromChild(data) {
console.log(data);
}
}
Finally in parent HTML
parent.component.html
<app-child (emitter)="receiveDataFromChild($event)"></app-child >
Hope it helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With