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

时间:2018-07-13 09:51:04

标签: javascript html angular

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

下面是我的代码:

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

3 个答案:

答案 0 :(得分:3)

好像您忘记在输入字段中添加Warning: SNMP::get(): No response from 127.0.0.1

<?php
    $session = new SNMP(SNMP::VERSION_1, "127.0.0.1", "public");
    $sysdescr = $session->get("sysDescr.0");
    echo "$sysdescr\n";
    $session->close();

编辑:做到这一点的方法

由于您正在使用Angular,因此我建议您使用NgModel

尝试一下

id

在组件中:

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

答案 1 :(得分:2)

您需要设置输入标签id删除ng-model,因为它是 angularjs(1.xx)而不是 angular(2/4/5/6) < / p>

以html

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

在打字稿中:

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

这是有效的示例:Get value of input tag using HTMLInputElement

答案 2 :(得分:0)

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