简体   繁体   中英

Angular 2 and EventEmitter

Hello I've started studying Angular 2. Maybe someone could help me with my question about EventEmitter and outputs in Angular 2

I have 3 components.

AppComponent is parent of CountriesListComponent .

CountriesListComponent is parent of CountryInfoComponent

AppComponent -> CountriesListComponent -> CountryInfoComponent

AppComponent has own function to listen when someone clicks on some country.

Template of AppComponent is like this:

@Component({


template: `...

< countries-list (OnCountrySelected)="countryWasClicked($event)" >
< /countries-list >
`
...

})

class AppComponent {
countryWasClicked(country: Country): void
  {

  }
}

The function OnCountrySelected is the name of output I want to listen. But I can listen it only in next child in CountriesListComponent , can't I? I want to listen OnCountrySelected in the CountryInfoComponent .

But I don't know if I can send output throught some childs.

Thanks in advance!

You can chain events for sure, but it is not a best practice. Like this inside the template of CountriesListComponent:

@Component({
template: `...
  < country-info (OnCountrySelected)="countryWasClicked($event)" >
  < /country-info >
`
...
})
class CountriesListComponent {
 @Output() OnCountrySelected:EventEmitter = ...
 countryWasClicked(country: Country): void
   {
     this.OnCountrySelected.emit(country);
   }
 }

But I would recommend to use (and learn) Redux approach for complex app state logic, you can use this: https://github.com/ngrx/store

This might help you find your answer (more specifically shared models or service events):

https://stackoverflow.com/a/34703015/6157104

you need an @Input() decorator in CountryInfoComponent, probably should name it country. and then in CountryListComponent you will give the selected country to the info component like this <app-country-info [country]="selectedCountry"> . selected country should be a public property of CountryListComponent. and its value can be set in your function already used to emit.

Long story short, it's an input decorator situation, not an output decorator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM