如何绑定组件变量以形成对象实例属性

时间:2017-04-30 12:20:12

标签: html5 forms angular angular2-ngmodel

我不太确定如何将组件类中的变量绑定到表单对象中的属性值。表单需要显示此值并将其添加到ngModel,以便它可以成为对象实例的一部分。

我正在努力学习语法并不断收到错误No value accessor for form control with name: 'per_print' Error: No value accessor for form control with name:我认为我需要使用[(ngModel)]="myObject.property"语法,但我不是从表单的输入中得到这个,而是从绑定班上的变量。

  <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>一样,但此错误仍然存​​在。

1 个答案:

答案 0 :(得分:2)

您可以将[hidden]输入字段与所需的值一起使用,以便将此值添加到表单中。但这意味着您需要使用pricePerPrint作为ngModel。但可能不需要ngModel job_entry。您可以这样构建表单,以便从表单中获取的对象可以直接分配给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

相关问题