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,
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';
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With