angularangular-changedetection

Angular Property Binding to New Object Instance


In Angular (15), if we have a component property (@Input) that is an object - for instance [config]="{ size: 10, label: 'hello' }" - is the object that is instantiated in HTML being recreated on every Change Detection Loop? Is it bad to do this directly in the template (HTML)?

I've seen this various times in examples and I'm not sure if it's just a lazy way to convey how things are done or if Angular is optimized enough to not recreate the object and just check its properties on Change Detection.

This question is interesting in the specific case where I use a Pipe to determine a value of the config-object. I make sure the Pipe is pure so it only evaluates if the input changes but that would be every time in the case where the object is created anew everytime.

For example [config]="{ size: someotherObject | calcSize, label: 'hello' }"


Solution

  • A string that creates an object will be evaluated on every change detection run. It might have a function call - at least because of that.

    It is not an expensive operation, but it will cause an additional CD run because the input of the child component has changed. Without the pipe, I would recommend moving it to the component, but with the pipe - it is better to leave it as is.