Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular(2+) : Mutating an input param in child component

Tags:

angular

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;
    }
}
like image 405
knomdlo Avatar asked Oct 14 '25 18:10

knomdlo


1 Answers

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:

  1. 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.

  2. 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.

like image 173
Sam YC Avatar answered Oct 17 '25 09:10

Sam YC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!