【问题标题】:Angular : Fetch value of textbox onclick of buttonAngular:获取文本框onclick按钮的值
【发布时间】:2018-07-13 09:51:03
【问题描述】:

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

下面是我的代码:

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

【问题讨论】:

  • 通常不鼓励在 Angular 应用程序中直接操作 dom。我会使用模板变量来引用输入并将值直接传递给 myFunc。

标签: javascript html angular


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您需要设置输入标签的 id 删除 ng-model 因为它是 angularjs(1.x.x) 而不是 angular(2/4/5/6/7/8)

    在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

    【讨论】:

    • 当我们可以使用可以保持正常的绑定时,为什么还要在这里使用“document.getElementById()”。
    • 使用“ViewChild”会更好。它更接近“Angular”方法。检查答案HERE
    【解决方案3】:
    <input type="text" class="textbox" id="Summary" name="Summary"placeholder="Summary" value="{{Item.summary}}">
    (document.getElementById("Summary") as HTMLInputElement).value;
    

    【讨论】:

    • 不鼓励仅使用代码回答,因为它们没有为未来的读者提供太多信息,请对您所写的内容提供一些解释
    猜你喜欢
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多