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

sTg*_*sTg 1 html javascript 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);
  }

}
Run Code Online (Sandbox Code Playgroud)

HTML文件

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

错误:

ERROR TypeError: Cannot read property 'value' of null
Run Code Online (Sandbox Code Playgroud)

Sau*_*wal 7

好像您忘记id在输入字段中添加

<input id="exchageRateDate" type="text" value="Sydney" ng-model="placeId" />
Run Code Online (Sandbox Code Playgroud)

编辑:角度方式来做到这一点

当您使用 Angular 时,我会建议您使用NgModel更好的方法来做到这一点

尝试这个

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

在组件中:

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