how to bind component variable to form object instance property


I am not quite sure how to bind a variable from my component class to a property value in my form object. The form needs to display this value and add it to the ngModel so that it can become part of the object instance.

I am struggling with the syntax and keep getting the errorNo value accessor for form control with name: 'per_print'
Error: No value accessor for form control with name:
I think I need to use the [(ngModel)]="" syntax, but I am not getting this from an input into the form, but from a binded variable on the 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'}}

job_entry is my object which properties I am setting through the form. pricePerPrint is a variable on the class. I want to set this variable to one of the form instance properties. How to do this? I thought I could do it through value, as in the value of the <h4> tag, but this error persists.


You could use [hidden] input field with the value you want, so that this value will be added to your form. This means though, that you need to use pricePerPrint as the ngModel. But ngModel for your job_entry is possibly not needed. You could build the form as such, so that the object you get from the form can be assigned directly to job_entry:

onSubmit(obj) {
  this.job_entry = obj;

Also check the Demo for that.

So your code would look like this:

<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>

where isHidden is set to true.

Other option I see, if you want to use [(ngModel)]="job_entry.per_print, you need to assign whatever value you have in pricePerPrint to job_entry.per_print.

Answered By – AT82

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.