Search code examples
htmlangularangular-reactive-forms

Angular FormControl on <input> displays [object Object]


Using Angular 7.

Have an <input> tag like the following:

<input id="foo" type="text" class="bar" [formControlName]="'product'" 
 autocomplete="off [ngModel]="formGroup.controls.product.value" [readOnly]="true"/>

Eventually, myControl.setValue('some string'); is called.

The result is the <input> element displays [object Object].

I am trying to display the string from the setValue() call.

What am I doing incorrectly?


Solution

  • try like this you don't need to use [ngModel] you set product control directly

    <div [formGroup]="form">
      <input id="foo" type="text" class="bar" formControlName="product" 
           autocomplete="off"  [readOnly]="true"/>
        <button (click)="update()">Update</button>
    </div>
    

    component

     form:FormGroup;
    
      constructor(fb:FormBuilder) {
          this.form = fb.group({
            product:'init data'
          });
      }
    
      update(){
        this.form.get('product').setValue('Updated...')
      }
    

    demo 🚀

    incase you just have single form control you have to use [formControl] directive

      <input id="foo" type="text" class="bar" [formControl]="myControl" 
           autocomplete="off"  [readOnly]="true"/>
        <button (click)="update()">Update</button>
    

    component

      myControl:FormControl
    
      constructor() {
          this.myControl = new FormControl('init data')
      }
    
      update(){
        this.myControl.setValue('Updated...')
      }
    

    demo 🌟