我想在单击按钮时打印文本框的值。但它会抛出空指针异常。我还需要在文本框中保留一些值,我不明白为什么?无论我在文本框中输入什么,当我单击按钮时,我都需要打印文本框的值,这是什么问题?
下面是我的代码:
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/