简体   繁体   中英

Angular : Fetch value of textbox onclick of button

I want to print the value of textbox when i click of button. But it throws nullpointerexception. I also need to keep some value in the textbox i dont understand why?. Whatever i type in textbox and when i click on buttom i need to print the value of textbox What is the issue?

Below is my code:

ts file

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

@Component({
  selector: 'app-mypage',
  templateUrl: './mypage.component.html',
  styleUrls: ['./mypage.component.scss']
})
export class mypageComponent implements OnInit {

  constructor(private router: Router) {

  }

  ngOnInit() {
  }



  myFunc() {

      var num1 = ((document.getElementById("exchageRateDate") as HTMLInputElement).value);
      console.log(num1);
  }

}

HTML File

<br>Welcome.<br>
Place - <input type="text" value="Sydney" ng-model="placeId" />
<button (click)="myFunc(placeId)" formtarget="_blank">Test</button>

Error:

ERROR TypeError: Cannot read property 'value' of null

Seems like you forgot to add id in input field

<input id="exchageRateDate" type="text" value="Sydney" ng-model="placeId" />

Edit : Angular way to do it

As you are using Angular so I will suggest you a better way to do this using NgModel

Try this

<br>Welcome.<br>
Place - <input type="text" value="Sydney" [(ngModel)]="placeId" />
<button (click)="myFunc(placeId)" formtarget="_blank">Test</button>

In component:

myFunc(num1) {
  console.log(num1);//here you will get input value through ng-model
}

You need to set id of input tag remove ng-model because it's a angularjs(1.xx) not angular(2/4/5/6/7/8)

In html

<br>Welcome.<br>
 Place - <input id="exchageRateDate" type="text" value="Sydney"  />
 <button (click)="myFunc()" formtarget="_blank">Test</button>

In typescript:

myFunc() {
    var num1 = ((document.getElementById("exchageRateDate") as HTMLInputElement).value);
    console.log(num1);
}

Here is working example: Get value of input tag using HTMLInputElement

<input type="text" class="textbox" id="Summary" name="Summary"placeholder="Summary" value="{{Item.summary}}">
(document.getElementById("Summary") as HTMLInputElement).value;

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