1

I have a container component which subscribes to an @ngrx/store and renders a list of components which internally have a form. The component hierarchy is like the following:

// orders-list.component.ts

export class OrdersListComponent {

  // more stuff
  
  ngOnInit() {
    this.orders$ = this.store.pipe(
      select(orderSelectors.selectAll)
    );
  }
  
  onOrderChange(id, changes) {
    this.store.dispatch(
      new OrderUpdateAction(id, changes);
    );
  }
}

// order.component.ts

export class OrderComponent {

  @Input() orderData;
  @Output() orderChange = new EventEmitter();

  // more stuff
  
  constructor() {
    this.form = this.formBuilder.group({ ... });
  }
  
  ngOnInit() {
    this.form.valueChanges.subscribe(value => {
      this.orderChange.emit(value);
    });
  }
  
  ngOnChanges() {
    this.form.patchValue(this.orderData);
  }

}
<orders-list>
  <order 
    *ngFor="let order of orders$ | async"
    [orderData]="order"
    (orderChange)="onOrderChange(order.id, $event)">
  </order>
</orders-list>

Idea is simple. When the value of the form changes, the inner component emits an event. The outer component uses the data from the event and dispatches an action to the store which updates the entity and passes back the updated entity to the inner component. The inner component then uses that to patch the value of the form.

Issue is that every time a form field changes, the element loses focus. If there is an input box or a select box or whatever the form control might be, on every dispatch the element loses focus.

Any help appreciated!

nerazzuri
  • 11
  • 2

0 Answers0