I got the following html
<app-grid [columns]="columns" [data]="data" ></app-grid>
I want the data and columns properties to be immutable. The Grid should only show it. But in cases of sort or filtering the data would change, at least the order.
But here is my problem. If I access the data array and modify one property of an containing object. Like this.
this.data[0].name = "test"
The original gets changed. But I thought [data] is only one way data bound.
Could somebody point me in the right direction, to why this is happening and how I can omit it. I come from React where this would be pretty straight forward.
One-way Data Binding. One-way data binding will bind the data from the component to the view (DOM) or from view to the component. One-way data binding is unidirectional. You can only bind the data from component to the view or from view to the component.
Angular v2+ supports two-way data binding using ngModel directive and also by having getter and setter methods.
One-way data binding in Angular (i.e. unidirectional binding) is a way to bind data from the component to the view (DOM) or vice versa - from view to the component. It is used to display information to the end-user which automatically stays synchronized with each change of the underlying data.
[ngModel]
, [value]
, {{ param }}
etc. you have one-way binding, model to view, (ngModelChange)
you have one-way binding, view to model, [(ngModel)]
you have two way binding.But you are using a sub-component with the input @Input()
property and this dances out of the line ;-) The notation is not what it looks like because it's always binded.
<sub-component [prop]="myObj"></sub-component>
So if you change the myObj in your sub-component, it will be binded:
ngOnInit() {
this.myObj = this.myObj.push(this.newObj);
}
You could work with a local copy of myObj to prevent binding.
If you need an update from model you can push it with @Output()
as Event:
<sub-component [prop]="myObj" (update)="myObj = $event"></sub-component>
You are right, syntax [target]=expression
is a one way data binding, but I think that you have misunderstood the idea of the one way data binding.
One way data binding from data source to the view target means that values from the view are not passed back to the component, while any changes made to the expression in the component are reflected in the view - it is one way data binding from data source to the view, what does not mean that it is one time one way data binding.
On the other hand you may find one way data binding from the view target to data source with syntax (target)=expression
which is used for passing events back to the components.
You can find more about Angular2 data binding in the docs here: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#binding-syntax.
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