<input>上的Angular FormControl显示[object Object]

时间:2019-12-19 20:03:24

标签: html angular angular-reactive-forms

使用Angular 7。

具有一个<input>标签,如下所示:

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

最终,将调用myControl.setValue('some string');

结果是<input>元素显示[object Object]

我正在尝试显示来自setValue()调用的字符串。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

尝试这种方法,您无需使用直接设置产品控制的[ngModel]

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

组件

 form:FormGroup;

  constructor(fb:FormBuilder) {
      this.form = fb.group({
        product:'init data'
      });
  }

  update(){
    this.form.get('product').setValue('Updated...')
  }

demo ?

如果您只有单个表单控件,则必须使用[formControl]指令

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

组件

  myControl:FormControl

  constructor() {
      this.myControl = new FormControl('init data')
  }

  update(){
    this.myControl.setValue('Updated...')
  }

demo ?

答案 1 :(得分:0)

删除输入的[ngModel]部分,如果您也使用formControlName,则不需要此部分。

设置值时,我们看不到您如何指定myControl,但等效代码为:

this.formGroup.controls['product'].setValue('my string');