【问题标题】:Angular binding @input behavior not working propertly角度绑定@input 行为无法正常工作
【发布时间】:2018-06-18 17:47:36
【问题描述】:

我在使用 Angular EventEmitter 和 Angular @Input 时遇到了一些问题。

我的应用有 3 个组件:2 个组件(TableComponentMapComponent)在它们之间不交互,还有一个额外的组件就像这两个组件的父级(BodyComponent)。

TableComponent 定义了以下@Input

  _oportunidades: Item[];
  @Input() set oportunidades(oportunidades: Item[]){
    debugger;
    this._oportunidades = oportunidades;
    this.dataSource = new MatTableDataSource<Item>(this._oportunidades);
    this.dataSource.paginator = this.paginator;
  }

MapComponent 定义:

 @Output() event_emitter_for_items_filtered_by_polygon = new EventEmitter<string[]>();
  send_new_map_information_to_body(){
    this.event_emitter_for_items_filtered_by_polygon.emit(this.items_filtered_by_polygon);
  }

  add_function_that_sends_filtered_items_to_body_after_polygon_is_draw(){
    var self = this;
    google.maps.event.addListener(this.drawingManager, 'polygoncomplete', function(polygon) {
      self.filter_items_by_polygon(polygon);
      self.remove_markers_from_map();
      polygon.setPath([])
      self.send_new_map_information_to_body();
    });
  }

当过程send_new_map_information_to_body 被触发时。将修改后的数据发送到BodyComponentBodyComponent 捕获它没有错误BodyComponent html 显示在这里:

<div class="analysis">
  <app-mapa (event_emitter_for_items_filtered_by_polygon)="items_filtered_by_polygon($event)" [items]="map_data"></app-mapa>
  <app-tabla [oportunidades]="oportunidades_filtradas"></app-tabla>
</div>

过程items_filtered_by_polygon 修改BodyComponent 中定义的oportunidades_filtradas 变量。到现在为止,一切正常。

  items_filtered_by_polygon($event){
    this.oportunidades_filtradas = []
  }

变量oportunidades_filtradas绑定到TableComponent中的oportunidades变量(如BodyComponenthtml所示),当items_filtered_by_polygon方法改变oportunidades_filtradas@Input() set oportunidades(oportunidades: Item[])不会被触发。因此,我的TableComponent 中没有显示任何更改。

当应用启动并且数据通过组件分发时,一切都按预期工作。就在这种情况下,当尝试按照说明修改TableComponent 内容时,什么也没有发生。

在 chrome 的 devtools 控制台中,没有显示任何错误。并且应用程序的流程并不奇怪,只是没有任何反应。 有时,我们认为修改正在完成,但也许它们延迟很可怕?也许是某种异步问题?

我是 Angular 的新手,也许我不理解某些东西。我的应用程序中的所有其他绑定都在工作...

你怎么看?欢迎任何帮助! 谢谢!

【问题讨论】:

  • 你在 BodyComponent 中使用ChangeDetectionStrategy.OnPush 吗?

标签: javascript angular typescript binding


【解决方案1】:

这听起来可能发生了更改检测问题。根据您的变更检测策略,可能会发生这样的事情。尝试在 items_filtered_by_polygon 函数中使用 ChangeDetectorRef.detectChanges() 来查看是否是问题所在。如果它有效,您可以将其留在那里或将其移除,并为未触发的输入使用 observable。

【讨论】:

  • 这解决了我的问题。感谢您的建议。总的来说,阅读此解决方案确实很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-20
  • 2016-10-24
  • 1970-01-01
  • 2015-11-24
  • 2015-11-18
相关资源
最近更新 更多