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

how to bind component variable to form object instance property

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

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

  <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 是 class 上的一个变量。我想将此变量设置为表单实例属性之一。这该怎么做?我以为我可以通过 value 来完成,就像在 <h4> 标签的 value 中一样,但是这个错误仍然存​​在。

您可以使用 [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