Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular4: Prevent rerendering component on input change

I've been struggling with some stuff in Angular4. Please consider this Plunker: https://embed.plnkr.co/Sh4LaBtXOfxTzeL996jb/

It's a simple app which has a list of 3 items. It displays those 3 items in a subcomponent that lets the user edit the item.

I want to update the state on every keystroke (keyup). As I emit the new value, the data in the parent component (App) is updated, which causes a rerender of all the item subcomponents, which in turn causes the input field stop being focussed (as it is replaced).

That means the user can only type a single character before needing to refocus the input.

Is there any way to prevent the rerender / keep the focus on the input or a better way to set it up alltogether?

As a temporary fix for this I'm now registering what field has been changed in localStorage and on ngAfterViewInit I'm resetting the focus... which works but is ugly. I feel there should be a better way?

(In the Plunker I've setup a very simple update but in my real app I'm using firebase, subscribing to the list info which gives me the list as a whole when it emits. When that happens I set this.list to the data that's emitted, which causes the rerender.)

Thanks!

like image 329
Meldon Avatar asked Aug 23 '17 15:08

Meldon


1 Answers

You could also use the ngFor track by function to prevent rerendering. When you use track by, Angular recreates DOM nodes when the specified attribute changes and only then, otherwise it reuses the DOM node and changes it.

Info about trackBy

like image 120
EldarGranulo Avatar answered Sep 28 '22 11:09

EldarGranulo