Best practices for avoiding emitting events inside ngOnChange?

91 Views Asked by At

What would be the best practice for avoiding event emitters inside ngOnChanges? Here is a small example:

export class HeroListComponent implements OnChanges {

  @Input()
  heroNames: string[] = [];

  @Output() 
  action: EventEmitter<string> = new EventEmitter();

  ngOnChanges(changes: SimpleChanges) {
    if (changes.heroNames?.currentValue?.length > 0) {
       action.emit(heroNames[0]);
    }
  }
}

This is just a dumb example, but what if my child component gets some new information from its parent that changes the internal state, which then must be communicated to sibling components.

The risk of using the emitter inside ngOnChanges is causing the infamous ExpressionChangedAfterItHasBeenCheckedError. I know the cause of this error, but what would be a good solution to better separate updating the internal state of the child component and notifying sibilings about changes caused by the new state.

You could use services, but this completely circumvents change detection. I know you can also wrap the call to emit inside a setTimeout(). Is using another life cycle hook an alternative?

1

There are 1 best solutions below

0
On

well it is not internal state, if it is needed for other elements.

Can you bring up calculation of that value to the parent component?

If no, angular uses resolvedPromise.then(() => ...) inside of ngModel directive sources to make such updates (so you will be able to refer to its model.error and other states inside of a parent template)