简体   繁体   English

无法使用form.value读取html输入字段值-angular5

[英]Cannot read html input field value using form.value - angular5

I am using angular 5 我正在使用角度5

In my html I generate the value of a input field using 在我的html中,我使用以下命令生成输入字段的值

<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 然后我想使用在我的component.ts中检索生成的值

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? 我可以解决这个问题吗?

使用[ngValue]指令。

the best way to achieve what you want is 实现您想要的最好的方法是

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

now in your component class you will have a variable called unitCost and you can get or set the value of the text field like this 现在在您的组件类中,您将有一个名为unitCost的变量,您可以像这样获取或设置文本字段的值

setting value - unitCost = 'value' gettingValue - unitCost 设置值-unitCost ='value'GettingValue-unitCost

let me know if this is clear or i will create an example for you 让我知道是否清楚,否则我将为您创建一个示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM