Passing Data From Child Component Into Parent Component
Solution 1
There are several ways to do it.
1) Using a service: A service generally has a single instance in the application and can be used to share data between the components easily. E.g. create a service userService and inject it in components where ever you want to use it.
2) using Emit: Emit is used to emit an event in the application and corresponding action can be taken.
this.eventInChild.emit(data);
Two actions can be taken on event emission.
- calling a function of parent :
<child-component (eventInChild)="parentFunction($event)"></child-component>
- Emitting from service and Subscribing to an event(can be subscribed in service as well as components) :
In Service It goes like this:
getEmitStatus() {
return this.eventInService;
}
//In component or service - to listen to event
this.subscription = this.userService.getEmitStatus()
.subscribe(item => {
//thing to do here
});
Solution 2
Like @SaUrAbHMaUrYa explained, you can emit data from child to parent, I would do something like this :
Parent
<page-login (on_user_has_logged_in)="userNow = $event"></page-login>
Child :
import {Output} from '@angular/core'
import {EventEmitter} from '@angular/core'
@Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
@Output() on_user_has_logged_in : EventEmitter<any> = new EventEmitter()
login(MyValue) {
this.on_user_has_logged_in.emit(MyValue)
}
}
nauval
Updated on June 14, 2022Comments
-
nauval almost 2 years
I have problems with my angular, here I have two components:
- MyApp (ParentComponent)
- LoginPage (ChildComponent)
I have a property
UserNow
in partsMyApp
and I want to set the value of the propertyUserNow
through the componentsLoginPage
. How to do it?I have tried (but did not give any influence)
Import {MyApp} from '../../app/app.component'; @Component({ selector: 'page-login', templateUrl: 'login.html' }) export class LoginPage { public app: any; login() { ... this.app = MyApp; this.app.userNow = MyValue; ... } }
-
Kunal Kakkad over 6 yearsI think the code should be:
this.on_user_has_logged_in.emit(MyValue)
instead ofthis.on_user_has_logged_in(MyValue)
. Correct me if I am wrong. -
Hadrien TOMA over 6 yearsYou are totally right @KunalKakkad, thank you for noticing it!