Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are changes in Input(() fields propagated to parent component?

My understanding is that I can pass data to child components using directive @Input(), and send data back to parent component using @Output() and with the appropriate emit. But I wasn't aware that changes data in the @Input() field would be sent to the parent. Is this correct?

I modified the component communication workbook to reproduce this https://input-params.stackblitz.io

Can you explain?

Thanks,

like image 970
user3784515 Avatar asked Jan 25 '23 00:01

user3784515


2 Answers

Yes you can pass the data to the child component by using @Input(). This is reference binded, So when you change the value in the child that gets reflected in the parent component also.

Using @Output() you can send any data from the child to parent component. But as the data passed is reference binded, the value gets changed in parent even though you don't pass it back using @Output().

But if you want change the value only in child component and not get the changed value in parent component you can make another copy of your array and pass that to the child component using @Input().

You can make copy of the original array by using:

let inputArray = _.cloneDeep(this.originalArray)

_ is the lodash library providing many such options.

To use lodash you have to add the below line in imports:

import * as _ from 'lodash';
like image 81
Minal Shah Avatar answered Jan 27 '23 15:01

Minal Shah


Inputs are normal variables, if you pass an object to an input angular passes its pointer, therefore parent and child components point to the same data and if you change inner parts of this data in a parent or in a child component it will be respected in both places, but if you reassign the property itself - it doesn't have the effect from child component, because it changes child pointer and next change detection cycle it will be set back to the parent value due to mismatched values.

If you pass a primitive to an input (string number boolean) it doesn't share the pointer and the effect isn't applicable.

like image 34
satanTime Avatar answered Jan 27 '23 13:01

satanTime