我不太确定如何将组件类中的变量绑定(bind)到表单对象中的属性值。表单需要显示该值并将其添加到 ngModel
以便它可以成为对象实例的一部分。
我在语法上遇到了困难,并且不断收到错误 No value accessor for form control with name: 'per_print'
Error: No value accessor for form control with name:
我想我需要使用[(ngModel)]="myObject.property"
语法,但我不是从表单的输入中获取它,而是从类上的绑定(bind)变量中获取它。
<div class="form-group">
<label class="label-text" >Per Print</label>
<div class="input-group" style="width:150px;">
<h4 [(ngModel)]="job_entry.per_print" name="per_print"
value='pricePerPrint' class="form-control"
>
{{pricePerPrint | currency:'GBP':true:'1.2-2'}}
</h4>
</div>
</div>
job_entry
是我的对象,我通过表单设置其属性。 pricePerPrint
是类中的一个变量。我想将此变量设置为表单实例属性之一。这个怎么做?我以为我可以通过value
来做到这一点,如 value
中所示<h4>
的标签,但此错误仍然存在。
最佳答案
您可以将[hidden]
输入字段与您想要的值一起使用,以便该值将添加到您的表单中。但这意味着您需要使用 pricePerPrint
作为 ngModel
。但您的 job_entry
的 ngModel
可能并不需要。您可以这样构建表单,以便从表单获取的对象可以直接分配给 job_entry
:
onSubmit(obj) {
this.job_entry = obj;
}
另请检查 Demo 为此。
所以你的代码将如下所示:
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm.value)">
<input [hidden]="isHidden" name="per_print"
[(ngModel)]="pricePerPrint" [value]="pricePerPrint"/>
<h4>Price: {{pricePerPrint}}</h4>
<button type="submit">Submit</button>
</form>
其中 isHidden
设置为 true
。
我看到的其他选项,如果您想使用[(ngModel)]="job_entry.per_print
,您需要将pricePerPrint
中的任何值分配给job_entry.per_print
。
关于html - 如何绑定(bind)组件变量形成对象实例属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706284/