简体   繁体   中英

How can I use ng-model to use the value of input field in Angular TypeScript?

I am trying to make a simple calculator to get the values of input fields and use it on the same page but ng-model doesn't output value of input field.

I tried the same code on JsFiddle and it works fine but I am not sure why it doesn't work on the application.

 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div class="panel panel-default" ng-app=""> <form class="form-group panel-body"> <input ng-model="totalitems" type="number"> </form> <br> <h2 class="label-default">{{totalitems}}</h2> </div> 

import { Component, Input, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'Product Cost Calculator';

}

My application name is "calc" and I use ng-app="calc" on the body tag.

I was using Angular 2 and in the view > form > input I used ng-model which is not compatible with Angular 2 and replaced with [(ngModel)] . I further revised the HTML code to get rid of the errors caused by using [(ngModel)] as I was using this in the form and input was missing name attribute. [(ngModel)] works when name attribute exists for input or place input without a form.

<div class="panel panel-default" ng-app="">
<form class="form-group panel-body">
  <input [(ngModel)]="totalitems"  type="number" name="total_items">
</form>
<br>
<h2 class="label-default">{{totalitems}}</h2>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM