Angular 2 - * ngFor with keychain is not updated when an object changes

I use key pipe in a * ngfor loop. Data is transferred in JSON.

@Pipe({ name: 'keys' }) export class KeysPipe implements PipeTransform { transform(value, args: string[]): any { if (!value) { return value; } let keys = []; for (let key in value) { keys.push({key: key, value: value[key]}); } return keys; } } 

-

 <div *ngFor="let item of jsonObject | keys"> <p>{{ item.value.code }}</p> </div> 

The problem is when I delete an item from JSON, ngFor is not updated.

I have already tried two options:

  • call this.applicationRef.tick (); after deleting an item without changes
  • unclean pipe " pure: false ". This led to the huge memory usage in chrome in hundreds of megabytes, and I had to kill the process.

If there is another way?

Thanks!

+5
source share
2 answers

One way you can try:

 delete(id) { this.jsonObject = this.jsonObject.filter(x => x.id !== id); } 

This way you will not mutate the original array. This critical thing for the pipe

see also

+5
source

Clean pipes do not start if the link or value is not changed. To fix this, add pure: false to your pipe decorator. See Pipes

ex.

 @Pipe({ name: 'keyVal', pure: false }) export class KeyValPipe implements PipeTransform { ... } 

EDIT I have not seen that the OP has already done this. Another option is to set a temporary variable and then assign jsonObject, creating a new link. You can also try deep copy from temp to jsonObject

+2
source

Source: https://habr.com/ru/post/1261595/


All Articles