Hello everyone. This might not be a good place to ask Angular specific questions. if I violate rules, please let me know so I could delete this topic.
Is it okay to mutate @Input object in child component which is sent from the parent? This way we don’t need to notify parent when we change some property as this JS object will reflect to parent automatically. If it’s not a good practice, can You please provide me a reason for this.
You can, but I don’t think you should. At least not directly. As when you change the input directly, and then it changes else where in the parent, you just lost what information is needed.
A better idea is to use a getter/setter approach
export class MyComponent {
private _myInternalProp;
@Input()
get publicProp() {
return this._myInternalProp;
}
set publicProp(val: any) {
this._myInternalProp = val;
}
}
Perhaps I’m not understanding it completely, but I fear @mhartington’s suggestion. I fear anything that diffuses responsibility for holding truth. I really really like having only one place to look for things, because when there are more, I have to worry about what happens when they don’t agree.
I find JavaScript object aliasing to be a very dangerous thing to play with, for similar reasons: when objects are mutable, I have to worry about ownership semantics. If they’re not, then I don’t.
So if I were in this situation, and I wanted to propagate changes back to a parent, I would do one of two things:
add a corresponding @Output() property and use that channel
turn my child component into a ControlValueAccessor, bind it to a FormControl, and use that mechanism for managing state
This all depends on the end goal really. With my approach, I look at it as a chance to normalize data being passed in. You could trigger some side-effects or just modify some finalized results. The effects don’t matter. But when parents passes in the data, the whole cycle gets triggered again.
This way, you avoid having two conflicted sources of truth. There is the one from the parent, and that influences how the child component process that data. Either way, the processing is the same.