Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Data From Child Component Into Parent Component

I have problems with my angular, here I have two components:

  • MyApp (ParentComponent)
  • LoginPage (ChildComponent)

I have a property UserNow in parts MyApp and I want to set the value of the property UserNow through the components LoginPage. 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;
        ...
    }
}
like image 480
nauval Avatar asked Dec 06 '16 09:12

nauval


People also ask

Can we pass props from child to parent component?

You can't pass props from child to parent in React, it's only one way (from parent to child). You should either: Put the state in the parent component and manipulate it from the child component by passing the setter function in the props.

How do I pass data from child to parent in Salesforce?

Send Data with the Custom EventUse a custom event to pass data from the child to the parent. Save the file. Notice we pass the onclick event to the handleMultiply function, which gets the button data-factor through the event. target.


1 Answers

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
}); 
like image 181
Saurabh Maurya Avatar answered Oct 28 '22 15:10

Saurabh Maurya