3
votes

Is there any way in angular 2 so that we can achieve one-way data binding like we have done in angular 1.

<!DOCTYPE html>
<html lang="en-US">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="">
<h4>please change the text box value to see the scenario</h4>
  <p>Name : <input type="text" ng-model="name" 
ng-init="name='change me '"></p>
  <h1>Hello {{name}}</h1>
<h2>One-way binding- </h2>
{{::name}}
</div>

</body>
</html>

How we can achieve this in Angular 2 way. what alternatives we have for this.

Note: I do not want to reflect changes on HTML only. I'll need the updated value @component end, but I don't want to display the changes on UI only

2
for your info. angular1 does 2 way binding by ng-model="name" - Wasif Khan
Please read the question carefully. ng-model works like 2 way, but on HTML u can see two places I'm accessing 'name' @Wasif-Khan - Ashish Ratan
:: is not one-way binding, it is one-time binding - Charlie Ng

2 Answers

6
votes

Two way data binding in Angular 2 works like below:

<input type="text"  [(ngModel)]="name">

One way data binding in Angular2 is achieved by removing paranthesis i.e [ngModel]

<input type="text"  [ngModel]="name" (ngModelChange)="onChange($event)">
onChange(newvalue) {
//work with newvalue
}

Hope it helps!

1
votes

You can do this way

 <input type="text"  [ngModel]="name">

Read more here