Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get value from textbox using typescript in angular 2

I am a beginner to angular2 / typescript I'm trying get numbers from two textboxes and adding both numbers and display the result using interpolation

@Component({
selector: 'my-app',
template: 
`<h1>Hello {{name}}</h1>
<h1>{{D}}</h1>
 <form>
  <p>first number:<input type="text" id="num1"></p>
  <p>second number:<input type ="text1" id="num2"></p>
  <h1> {{result}}</h1>
  </form>
   <test-app></test-app>`
  })

  export class AppComponent 
  { 
 name = 'Angular'; 
 value : number;value1 : number;result:number;
  constructor(value : number,value1 : number,result:number)
  {

  this.value = parseFloat
  ((document.getElementById("text") as HTMLInputElement).value);
  this.value1 = parseFloat((document.getElementById("text1") 
  as HTMLInputElement).value);
  this.result=this.value+this.value1;
  }}
like image 662
ngopal Avatar asked Apr 14 '17 10:04

ngopal


1 Answers

The easiest way is to use template reference variable:

@Component({
  selector: 'app-little-tour',
  template: `
    <input #newHero > 
    <button (click)="addHero(newHero.value)">Add</button>
})

export class LittleTourComponent {
  addHero(newHero: string) {
    console.log(newHero)
  }
}

A complete guide for User Input in Angular can be found here: https://angular.io/guide/user-input

like image 106
ttfreeman Avatar answered Sep 28 '22 09:09

ttfreeman