Anouar Anouar - 12 days ago 6
TypeScript Question

Update a specific component using redux

Im using redux, for dispatching an expand event from a component to an another.

These components are used inside a table:

<table class="table table-bordered">
<thead>
<tr>
<th *ngFor="let business of businesses">
<app-business-header-cell [business]="business"></app-business-header-cell>
</th>
</tr>
</thead>
</table>


My header component:

export class BusinessHeaderCellComponent implements OnInit {

@Input()
business: Business;

@select() columnState$: Observable<any>;

constructor(private ngRedux: NgRedux<IAppState>) { }

ngOnInit() {
}

onClickExpand(){
this.ngRedux.dispatch({ type: 'EXPAND', id: this.business.id });
}

onClickCollapse(){
this.ngRedux.dispatch({ type: 'COLLAPSE', id: this.business.id });
}

}


The dispatch and the state update are working fine.

My problem is that when i dispatch my action EXPAND, it's intercepted by all the other header component. Is there a way to make a distinction for which component should be updated?

Answer

The simplest solution i've come up with:

export class BusinessHeaderCellComponent implements OnInit {

  @Input()
  business: Business;

  @select() columnState$: Observable<any>;

  constructor(private ngRedux: NgRedux<IAppState>) { }

  ngOnInit() {
    // ADDED THIS
    this.columnState$.subscribe(state => {
      if(this.business.id == state.id) this.isExpanded = state.isExpanded;
    });
  }

  onClickExpand(){
    this.ngRedux.dispatch({ type: 'EXPAND', id: this.business.id });
  }

  onClickCollapse(){
    this.ngRedux.dispatch({ type: 'COLLAPSE', id: this.business.id });
  }

}
Comments