One way data binding in Angular2

  • if you use [ngModel], [value], {{ param }} etc. you have one-way binding, model to view,
  • if you use (ngModelChange) you have one-way binding, view to model,
  • if you use [(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.


From Angular official documentation:

enter image description here

Tags:

Angular