spliitzx
spliitzx

Reputation: 11

How to pass child variables to parent in Angular?

I'm using two components, SelectTag and the main component, SettingsComponent. The select component is a simple directive with a selector, but the issue I'm having is updating a parent variable from the child component.

For example: I have an ngModel binding to a variable (name) in the selector component, but how can I access this from the parent component (settings)?

What I've tried so far is using the Angular EventEmitter:

@Output() onNameChange: EventEmitter<string>;

...and accessing it through

<select-tag (onNameChange)="name = $event">

Is there a better practice to doing this?

Upvotes: 0

Views: 4212

Answers (2)

Ethan Vu
Ethan Vu

Reputation: 2987

You can create a centralized centralized.service.ts component to distribute the data to your components, this way you get it centralized and easy to control the data flow when your app grow:

export class CentralizedService {
   private sharedData = {};

   getSharedData(){
      return this.sharedData
   }

   updateSharedData(data){
     //Statements 
   }
}

And inject the service to your module and get access to it in both your component

constructor(private centralizedService: CentralizedService){}

ngOnInit(){
 this.componentData = this.centralizedService.getSharedData();
}

//Create a method to update shared data 
updateSharedData(data) {
 this.centralizedService.updateSharedData(data);
} 

Upvotes: 1

Eliran Eliassy
Eliran Eliassy

Reputation: 1600

You have a few options to share data between Child and Parent Components. The best way is probably using an EventEmitter like you already tried, just make sure to trigger the event when you want to update. For example:

export class ChildComponent {

  @Output() nameUpdate: EventEmitter<string> = new EventEmitter<string>();
  updateParent(name){
    this.nameUpdate.emit(name)
  }

}

child.component.html:

<input (input)="updateParent($event.target.value)">

Now the parent who's using this child selector can listen to the nameUpdate event:

<app-child (nameUpdate)="nameUpdate($event)">

You will get the new value within the $event.

You can also consider using services and DI to share data across components, or any other state management tools. But, if your components are in a sibling relationship, Use the Input and Output decorators as the best practice.

Upvotes: 2

Related Questions