【问题标题】:Angular 2 and EventEmitterAngular 2 和 EventEmitter
【发布时间】:2016-07-15 03:51:43
【问题描述】:

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

我有 3 个组件。

AppComponentCountriesListComponent 的父级。

CountriesListComponentCountryInfoComponent 的父级

AppComponent -> CountriesListComponent -> CountryInfoComponent

AppComponent 有自己的功能,可以在有人点击某个国家/地区时进行监听。

AppComponent的模板是这样的:

@Component({


template: `...

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

})

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

  }
}

函数OnCountrySelected 是我要监听的输出名称。但是我只能在CountriesListComponent 的下一个孩子中听,不是吗? 我想在CountryInfoComponent 中收听OnCountrySelected

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

提前致谢!

【问题讨论】:

    标签: angular eventemitter


    【解决方案1】:

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

    @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

    【讨论】:

      【解决方案2】:

      这可能会帮助您找到答案(更具体地说是共享模型或服务事件):

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

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 2017-10-24
          • 1970-01-01
          • 1970-01-01
          • 2016-09-10
          • 2017-02-02
          • 2017-01-03
          • 1970-01-01
          • 1970-01-01
          • 2016-02-05
          相关资源
          最近更新 更多