Angular2更新表单控件值

Sil*_*cer 25 angular2-forms angular

我在使用控件和选择框构建动态angular2表单时遇到问题,例如这个plunker:

    <select class="form-control" ngControl="power">
      <option *ngFor="#p of powers" [value]="p">{{p}}</option>
    </select>
Run Code Online (Sandbox Code Playgroud)

您可以选择英雄力量,控件将具有相同的值.但是如果按Change Powers,则所选值将为null,但控制值仍为旧值.这是一个严重的问题,我认为这是一个很多错误的来源,当表单显示一件事,但实际上它会提交一些不同的东西,有没有办法更新控件的内容?有updateValue(),但是你必须手动设置在所有这些情况下的价值.

在表单构建之后更新selectbox选项时也会出现类似的情况,它会在selectedbox中显示一个选定的值,而控件值将为null,有关如何处理此问题的任何想法?

Ang*_*ity 26

在Angular 2 Final(RC5 +)中,有用于更新表单值的新API.该patchValue()API方法支持部分格式的更新,在这里我们只需要指定某些字段:

this.form.patchValue({id: selected.id})
Run Code Online (Sandbox Code Playgroud)

还有一个setValue()API方法需要一个包含所有表单字段的对象.如果缺少某个字段,我们将收到错误消息.

  • 只是补充说,现在`updateValue`(来自第一个答案之一)被弃用,转而支持`setValue` (6认同)

Par*_*ain 15

更新

截至最新的angular2语法更新将是这样的

this.form.controls['power'].setValue('anthing here');
Run Code Online (Sandbox Code Playgroud)


Gün*_*uer 6

目前这是你唯一可以做的事情(如问题所述)

this.form.controls['power'].updateValue(null);
Run Code Online (Sandbox Code Playgroud)

有一个未解决的问题,允许重置表单https://github.com/angular/angular/issues/4933

还有一个拉取请求,但也允许你为每个控件"手动",但也允许重置状态,如原始,触摸,... https://github.com/angular/angular/pull/6679


Jam*_*mon 5

[Angular 2稳定版]

这只是使用NgModel的一种肮脏方式(并且不导入其他表单构建器或表单组模块)

//
// set form field, "foo" value to "bar"
//

//
// view
//
<form #formRef="ngForm">
    <input name="foo" [(ngModel)]="foo"></input>
</form>

//
// controller
//
class {
    @ViewChild('formRef') form: NgModel;

    ngAfterViewInit() {
        setTimeout(() => {
          this.form['controls']['foo'].setValue('bar');
        });
    }
}
Run Code Online (Sandbox Code Playgroud)