简体   繁体   English

Angular:点击按钮时获取文本框的值

[英]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 .ts 文件

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 HTML文件

<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好像您忘记在输入字段中添加id

<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当您使用 Angular 时,我会建议您使用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)您需要设置输入标签的 id 删除 ng-model 因为它是angularjs(1.xx)而不是angular(2/4/5/6/7/8)

In html在 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这是工作示例:使用 HTMLInputElement 获取输入标签的值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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