Reputation: 3156
As I understand it, the Input
fields in a component are supposed to be one directional (parent to child). However, I have a value I'm passing into an Input
and then modifying it in the component, but I'm noticing it changes in the parent as well. That makes some sense to me, as objects are passed by reference, but I'm guessing that means that the whole "one way binding" thing Angular sets is just a paradigm, not strict? Angular does nothing under the hood to enforce one way binding?
Basically, I'm doing:
<session-form [values]="session"></session-form>
In the session-form
component, I change session.start
from a unixtimestamp to a Moment object. But I then notice in the parent, session.start
is also a Moment object.
Is there a paradigm for using data like this? Should I be copying input values to a variable scoped strictly to the component once it's set?
Upvotes: 5
Views: 2072
Reputation: 2131
Look into the smart/dumb (container/presentational) component architecture.
Basically the idea is that smart components contain the state of your app or talk to a service that contains the state. The dumb components just render the data given to it from the @Input. The smart components pass the state to the dumb component.
Instead of directly updating the data in the dumb component you use an event emitter to tell the smart component to update the data. This way you have the one way data flow.
More info here: http://blog.angular-university.io/angular-2-smart-components-vs-presentation-components-whats-the-difference-when-to-use-each-and-why/
Upvotes: 2
Reputation: 6577
Yes, objects are passed by reference. However, you should not bind properties of your object to the form using [(ngModel)]
because it's two-way binding and since object is passed by reference it reflects the changes to it inside the parent component as well. You should instead create a FormGroup
and pass the object values to it using a FormBuilder.group()
function since it's one directional.
// Inside of your child component
@Input() myInput: SomeClass;
form: FormGroup
constructor(
private formBuilder: FormBuilder
) { }
ngOnInit(): void {
this.form = this.formBuilder.group({
prop1: [this.myInput.prop1],
// etc.
});
}
Upvotes: 0