Cannot read html input field value using form.value - angular5

时间:2018-06-19 11:10:49

标签: html angular typescript angular5

I am using angular 5

In my html I generate the value of a input field using

<input type="number" class="form-control" id="unitCost" name="unitCost"    [(ngModel)]="unitCost" placeholder="Average Unit Price">
document.getElementById("unitCost").value = avgVal;

then I want to retrieve that generated value in my component.ts using

this.unitCost = form2.value.unitCost;

But it returns null value. instead if I type any value in the text field it works fine and returns the value I typed. Can I solve this issue?

2 个答案:

答案 0 :(得分:0)

Use [ngValue] directive of angular.

答案 1 :(得分:0)

实现所需目标的最佳方法是

<input type="number" class="form-control" id="unitCost"  [(ngModel)]="unitCost" placeholder="Average Unit Price">

现在在您的组件类中,您将有一个名为unitCost的变量,您可以像这样获取或设置文本字段的值

设置值-unitCost ='值' GettingValue-unitCost

让我知道是否很清楚,否则我会为您创建一个示例