1

What is the best to handle reference type data, for example json data, bind to a component. For example,

<my-component [data]="jsonData"></my-component>

where in .ts jsonData= {'key1':'value1','key2','value2'}

Now if on button click I change my jsonData as {'key1':'valueX','key2','value2'}

Angular won't be able to detect this change, hence doesn't run ngOnChanges(),because angular only checks reference of the data-binding changed or not as a result view won't be refreshed. How should I deal with it?

I can put logic to refresh my view in ngDoCheck() but it is called a lot of times. If json is large, then processing it each time ngDoCheck runs can be an expensive operation.

One possible solution I could think of is to make a service for that component, and on button click, pass the new json to that service, service will publish that event with changed data to my component and component, listening for the events of service, will refresh the view with that new data.

Is there any easier way to handle JSON/Array changes bind to component?

2
  • 1
    Have you tried two way data binding [(data)]="jsonData" ? Commented Jul 25, 2018 at 3:40
  • No, but is it going to call ngOnChanges() so that I can update my view? Commented Jul 25, 2018 at 13:48

1 Answer 1

1

You can use a setter for @Input property in your component.

Intercept input property changes with a setter

Use an input property setter to intercept and act upon a value from the parent.

@Input() set data(jsondata: any) {
   this._data = jsondata;
}

Refer to the documentation here for more details.

Update after comments:

Yes you can implement ngOnChanges as well for this, as the documentation states:

You may prefer this approach to the property setter when watching multiple, interacting input properties.

See the below example from the documentation,

export class MyComponent implements OnChanges {

   ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
      for (let propName in changes) {
         let changedProp = changes[propName];

         let to = JSON.stringify(changedProp.currentValue);
         if (changedProp.isFirstChange()) {
             console.log(`Initial value of ${propName} set to ${to}`);
         } else {
             let from = JSON.stringify(changedProp.previousValue);
             console.log(`${propName} changed from ${from} to ${to}`);
         }
      }
   }
}

You can get hold of the old and new values of your members using previousValue and the currentValue properties respectively.

Sign up to request clarification or add additional context in comments.

1 Comment

It solved my issue. Thanks. So when should one go for ngOnChanges() and this approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.