javascript - Angular : Fetch value of textbox onclick of button

标签 javascript html angular

我想在单击按钮时打印文本框的值。但它会抛出空指针异常。我还需要在文本框中保留一些值,我不明白为什么?无论我在文本框中输入什么,当我单击按钮时,我都需要打印文本框的值,这是什么问题?

下面是我的代码:

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

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

错误:

ERROR TypeError: Cannot read property 'value' of null

最佳答案

似乎您忘记在输入字段中添加id

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

编辑: Angular 方式来做到这一点

由于您使用的是 Angular,所以我会建议您使用 NgModel 更好的方法来做到这一点

试试这个

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

在组件中:

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

关于javascript - Angular : Fetch value of textbox onclick of button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51322407/

相关文章:

javascript - 在 WebStorm 中通过断言的测试失败

angular - 使用弹出的 Angular 4 应用程序进行生产编译会产生大文件

angular - 两个Ionic2菜单 : One is shown. 另一个不是

javascript - Angular 5 接口(interface)变量无法分配给类型问题

javascript - 对象构造函数和 TypeError 中的递归函数

javascript - 有什么方法可以查看代码的哪一部分使网页速度变慢?

无法从另一个属性(函数)访问 Javascript 对象属性

html - 响应式 div block

javascript - Html bootstrap alert 自动关闭困难

javascript - 任何让我的 javascript + html 代码更小的建议