繁体   English   中英

Angular 2和EventEmitter

[英]Angular 2 and EventEmitter

您好,我已经开始研究EventEmitter 。也许有人可以帮助我解决有关Angular 2中的EventEmitteroutputs问题

我有3个组成部分。

AppComponent是父CountriesListComponent

CountriesListComponentCountryInfoComponent父级

AppComponent - > CountriesListComponent - > CountryInfoComponent

当有人点击某个国家/地区时, AppComponent具有自己的侦听功能。

AppComponent模板是这样的:

@Component({


template: `...

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

})

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

  }
}

函数OnCountrySelected是我要收听的输出的名称。 但我只能在下一子听它CountriesListComponent ,不行吗? 我要听OnCountrySelectedCountryInfoComponent

但是我不知道我是否可以通过一些孩子发送输出。

提前致谢!

您可以肯定地链接事件,但这不是最佳实践。 在CountrysListComponent的模板中像这样:

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

但是我建议对复杂的应用程序状态逻辑使用(并学习)Redux方法,您可以使用此方法: https : //github.com/ngrx/store

这可以帮助您找到答案(更具体地讲,共享模型或服务事件):

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

您需要在CountryInfoComponent中使用@Input()装饰器,可能应该将其命名为country。 然后在CountryListComponent中,将所选国家/地区提供给信息组件,例如<app-country-info [country]="selectedCountry"> 所选国家/地区应该是CountryListComponent的公共属性。 它的值可以在已经用于发射的函数中设置。

长话短说,这是输入装饰器的情况,而不是输出装饰器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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