HOAB

History of a bug

Angular @Input array was not updated.

Rédigé par gorki Aucun commentaire

Problem :

Here again, a common problem, the @Input attribute of the child element was not updated.

Good to know : 

  • ngOnChanges is called when the @Input attribute is already updated
  • common problem : the @Input parameter is an array and its reference is not modified, i.e, the array is the same even if it has different elements or new elements

No, in my case, the symptoms was : 

  1. ngOnChanges input is launch
  2. SimpleChanges event contains the data in “currentValue
  3. but array is displayed as [] even with values.

Yeah, tricky. I understand that array may be an object instead of a real array… but why. 

Solution :

Part of the problem was that the value sent to @Input was an array, but not initialized.

And a small function used to have unique value : 

  private pushIfNotExist<T>(array:T[], element:T) {
    if (array.indexOf(element) === -1) {
      array.push(element);
    }
  };

and I call it like that : 

pushIfNotExist(myArray, randomValue)

And with an empty javascript variable, well : no problem, it works, in a given way.

Adding : 

myArray = []

just before, everything works as a charm.

I lose time here, because I had a doubt on where was the issue : display on browser console, workflow for triggering ngOnChange, …

 

 

Lire la suite de Angular @Input array was not updated.

Fil RSS des articles de ce mot clé