繁体   English   中英

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

[英]Angular : Fetch value of textbox onclick of button

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

下面是我的代码:

.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 时,我会建议您使用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
}

您需要设置输入标签的 id 删除 ng-model 因为它是angularjs(1.xx)而不是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);
}

这是工作示例:使用 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