-2

I need help, at the last days I was tring to pass data between components... I followed alot of samples around internet, and none of those works.

The most tutorials says to me to use @input and @output. i think this is the most correct way to pass data in angular...

Here is my structure:

The componentA is called in html of componentC, like this:

<app-componentA</app-componentA>

The componentB is called via modalController

my structure

in my actual code, i pass the data generated in componentB to componentC like this:

// componentB.ts
  dimiss(filters?: any) {
    this.modalController.dismiss(filters);
  }

and recive in componentC:

// componentC.ts
const filters = await modal.onDidDismiss();
this.Myfilters = filters ;

now how i pass the data from componentB to ComponentA?

Igor
  • 399
  • 4
  • 18
  • Use a shared service. – Reactgular Aug 16 '19 at 16:45
  • An input looks fine to me. What's the concrete problem when you use one? Post a complete minimal example reproducing the problem, and explain what the problem is. Saying that none of what you tried worked without posting what you tried and explaining what "doesn't work" mean makes it impossible for us to help you. – JB Nizet Aug 16 '19 at 16:50
  • Passing data using Input and Output, of course, is the correct way of passing data between components. If you would like to pass it using some shared service and rxjs remember to unsubscribe when you will destroying your components. – Stefan Aug 16 '19 at 16:53

1 Answers1

0

Although it depends on your app, generally speaking, the best way to move data around inside an Angular app is through a service. You inject the service in all of the components where you need the shared data. Here is a simple example.

In FirstComponent:

isLoggedIn: boolean;

constructor(private myService: MyService) {}

ngOnInit() {
  this.isLoggedIn = this.myService.getLoggedInStatus();
}

In SecondComponent:

constructor(private myService: MyService) {}

onLogin(loginData) {
  this.myService.login(loginData);
}

And in MyService:

private isLoggedIn = false;

getLoggedInStatus() {
  return this.isLoggedIn;
}

login(loginData) {
  if (loginData === valid) {
    this.isLoggedIn = true;
  }
}

In this example, events and data are stored and modified centrally in the service, and each component grabs what it needs. For more info on Angular services, check out the docs here: https://angular.io/guide/dependency-injection

Will Alexander
  • 3,425
  • 1
  • 10
  • 17