简体   繁体   English

Angular2 更新表单控件值

[英]Angular2 update form control value

I have a problem building dynamic angular2 forms with controls and select boxes, for example this plunker :我在使用控件和选择框构建动态 angular2 表单时遇到问题,例如这个plunker

    <select class="form-control" ngControl="power">
      <option *ngFor="#p of powers" [value]="p">{{p}}</option>
    </select>

You can select a hero power, and the control will have the same value.您可以选择英雄的力量,并且控制将具有相同的值。 But if you press Change Powers , the selected value would be null but the control value is still the old value.但是,如果您按Change Powers ,则所选值将为空,但控制值仍然是旧值。 This is a serious problem I think as this is a source of a lot of bugs when the form shows one thing but in reality it will submit something different, is there some way to update the content of the control ?我认为这是一个严重的问题,因为当表单显示一件事但实际上它会提交不同的内容时,这是许多错误的来源,有什么方法可以更新控件的内容吗? There is updateValue() but you have to manually set the value in all those cases.updateValue()但您必须在所有这些情况下手动设置该值。

There is also a similar case when you update the selectbox options after the form building, it will show a selected value in the selectedbox, while the control value would be null, any ideas on how to deal with this ?还有一个类似的情况,当你在表单构建后更新selectbox选项时,它会在selectedbox中显示一个选定的值,而控件值为null,请问如何处理?

In Angular 2 Final (RC5+) there are new APIs for updating form values.在 Angular 2 Final (RC5+) 中有用于更新表单值的新 API。 The patchValue() API method supports partial form updates, where we only need to specify some of the fields: patchValue() API 方法支持部分表单更新,我们只需要指定部分字段:

this.form.patchValue({id: selected.id})

There is also the setValue() API method that needs an object with all the form fields.还有setValue() API 方法需要一个包含所有表单字段的对象。 If there is a field missing, we will get an error.如果缺少字段,我们将收到错误消息。

Update更新

as of latest Update of angular2 syntax will be like this截至 angular2 语法的最新更新将是这样的

this.form.controls['power'].setValue('anthing here');

Currently this is the only thing you can do (as mentioned in the question)目前这是您唯一可以做的事情(如问题中所述)

this.form.controls['power'].updateValue(null);

There is an open issue to allow to reset a form https://github.com/angular/angular/issues/4933有一个开放问题允许重置表单https://github.com/angular/angular/issues/4933

There is also a pull request but that also allows you to to it "manually" for each control but also allows to reset states like pristine, touched, ... https://github.com/angular/angular/pull/6679还有一个拉取请求,但它也允许您为每个控件“手动”设置它,但也允许重置状态,如原始、触摸、... https://github.com/angular/angular/pull/6679

[Angular 2 Stable] [Angular 2 稳定]

Here's a dirty way just using NgModel (and without importing other form-builder or form-group modules)这是仅使用 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');
        });
    }
}

You can try to keep form sort of immutable.您可以尝试使表单保持不变。 When you need to reset it you just rebuild it.当您需要重置它时,您只需重建它。 This way can be sure it's up to date.这样可以确保它是最新的。 You can also keep values stored somewhere and reset form to those values.您还可以将值存储在某处并将表单重置为这些值。 Say you're editing an item, when you reset you can revert to the original values, not just an empty form...假设您正在编辑一个项目,当您重置时,您可以恢复到原始值,而不仅仅是一个空表单......

export class TheForm {
  public form: ControlGroup;
  public controls = (value: any = {}) => ({
    'id': [value.id],
    'name': [value.name, Validators.required]
  });

  constructor() {
    let values = some_values_from_database || {};
    this.build(values);
  }

  build(value) {
    this.form = this._builder.group(this.controls(value));
  }

  submit() {
    console.log(this.form.value);
  }
}

I've created the base form that handles this kind of functionality with @ngrx/store , here's the Gist .我已经使用@ngrx/store创建了处理这种功能的基本表单,这里是 Gist When I need a form for different model, I'll extend BaseForm and just define controls and submit() method, the rest is inherited...当我需要不同模型的表单时,我将扩展BaseForm并只定义controlssubmit()方法,其余部分继承...

代码是:

(<FormControl>this.form.controls['power']).updateValue(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM