Is mutating an input param in a child component fine or should all input objects be considered read-only & then emit event for any changes back to parent & delegate the change to parent component? Are there any problems that could arise out of modifying input params.
class ChildComponent {
@Input() parentParam;
@Output() clickValEvent = new EventEmitter<boolean>();
let parentParamClone = Object.assign({}, parentParam);
childClickEvent(val) {
//Update value locally.
// parentParam.clickVal = val;
//Inform parent & let it do necessary change.
// this.clickValEvent.emit(val);
//Only play with local clone.
// parentParamClone.clickVal = val;
}
}
By right, yes, you can modify the @input
value in child component, it will reflect in your parent component. But then there are 2 reasons you should avoid this:
it will not work for primitive value, if you expect to change @input
primitive value and it reflect in your parent component, this will not work.
this is not a good practice, it open the chance for all the children component to arbitrary update the @input
object and make us hard to trace the value changes. So using @output
save us a lot of effort in future in maintaining the code, because it is more declarative.
I find it weird that, I couldn't find any official explanation regarding to this from Angular docs. Unlike ReactJs
and VueJs
, they very discourage us to mutate the props
in child component.
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