Angular 2组件之间的同步数据变得疯狂

时间:2016-05-08 09:16:52

标签: angularjs typescript angular

我正在尝试在两个角度组件之间同步数据。然而,它的功能有点不可预测。

我有父组件,它提供数据(同步):

@Component({
  /*...*/
  directives: [TbInfiniteScrollComponent],
  viewBindings: [TbInfiniteScrollComponent],
  providers: [TbService],
  encapsulation: ViewEncapsulation.None
})

export class TbNiV3AppComponent {
  public dealerList:Array<Object> = []

  constructor(service: TbService, private cdr:ChangeDetectorRef) {

    this.dealerList = service.data.flatten(service.data.get());

  }

  syncData(data){

    /* Unfortunately this doesn't work */

    console.log('syncData!', this.dealerList);
    this.dealerList = [].concat(data);
    this.cdr.markForCheck();
  }
}

及其HTML

 <tb-infinite-scroll [tbScrollData]="dealerList" *ngIf="dealerList" (tbDataSync)="syncData($event)" [tbIndent]="true">
   Loading Tree Component...
 </tb-infinite-scroll>
 <tb-infinite-scroll [tbScrollData]="dealerList" *ngIf="dealerList"  (tbDataSync)="syncData($event)">
   Loading Tree Component...
 </tb-infinite-scroll>

然后我有子组件

@Component({
  /* ... */
  selector: 'tb-infinite-scroll',
  inputs: ['rows:tbScrollData', 'tbElHeight:elementHeight', 'tbIndent'],
  outputs: ['tbDataSync'],
  encapsulation: ViewEncapsulation.None,
  providers: [TbInfiniteScrollService, ChangeDetectorRef],
})

export class TbInfiniteScrollComponent {

  public tbDataSync:EventEmitter<any> = new EventEmitter()

  private rows:Array<Object> = []

  /* ... */

  assignRows() {
     this.visibleRows = this.service.assignVisible(this.rows, this.elementHeight, this.scroll);
  }

  constructor(private service:TbInfiniteScrollService, private elementRef:ElementRef, private cdr:ChangeDetectorRef) {
  }   

  toggleVisible(children) {
    this.service.changeVisibility(children);
    this.assignRows();
    this.tbDataSync.emit(this.rows);
  }

}

并排行HTML

 <div class="tb-infinite-scroll__row"
       *ngFor="let row of visibleRows"
       [ngStyle]="{'margin-left': (tbIndent ? (row.level - 1) * 15 : 0) + 'px'}"
       (click)="row.children && toggleVisible(row.children)">
    {{row.name}}
  </div>

它的作用:它在单击后更改数据对象子项的visible属性,并且仅呈现带有visible === true的元素。由于两个组件通过父控制器共享相同的数据集,我希望它们呈现相同的输出。但是,在我单击要更新的一个组件中的一行后,第二个组件也应该更新,但它会随机发生。

我相信这个gif会更好地解释我的问题。

enter image description here

当绑定数据更改时,如何强制组件从父组件刷新? 提前谢谢!

编辑:数据对象通过引用链接

0 个答案:

没有答案