Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 679
springandangular Avatar asked Dec 05 '25 21:12

springandangular


1 Answers

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 🌟

like image 161
Muhammed Albarmavi Avatar answered Dec 07 '25 12:12

Muhammed Albarmavi