I'm fairly new to Angular, hoping someone can shed some light on this.
Method 1: Say I'm passing a parent object 'x' to a child component using 1 way data binding:
<app-child [x]="x"></app-child>
and my child component modifies it like so in ts:
Input() x;
then later:
this.x.someProperty = 'some new value';
This seems to work fine, my 'x' object in the parent is updated.
However in Angular tutorials & other examples (eg https://stackoverflow.com/a/41465022) it seems the 'proper' way to do this would be Method 2: to use 2 way binding eg:
<app-child [(x)]="x"></app-child>
and in the ts
@Input() x: any;
@Output() xChange = new EventEmitter<any>();
then later:
this.x.someProperty = 'some new value';
this.xChange.emit(x);
I'm currently very happily using Method 1 in Angular 7 without any problems - can anyone explain why (if at all) I should use method 2 instead? It seems more complicated & unnecessary since Method 1 works.
You are using an object, and objects are passed by reference and are mutable.
If you were to use a primitive value like, boolean
, which is used in the link you provided, then modifying the variable in the child would not reflect in the parent. You can see it per this demo, where we a using a string, which is also a primitive. For achieving that parent would get the value too, you would need to use Output
. Choosing to use two-way-bindning i.e
[(something)]="something"
or not, is up to you. You could also use one-way-binding the both ways, like:
[something]="something" (somethingHasChanged)="parentFunction($event)"
So two-way-binding is just a shorthand for the above.
So as mentioned, objects (and arrays) are mutable, so it's important to remember if you some time do not want to reflect changes in parent of what you do in child component.