简体   繁体   中英

How to iterate over a formbuilder in Angular2?

I try to iterate over a form control but get some problem. I use the FormBuilder from Angular2.

I have following code in my controller:

ngOnInit() {
    let data = this.dataSet[this.key];
    this.form = this._fb.group({});

    Object.keys(data).forEach(name => {
      this.form.addControl(name, new FormControl());
      this.form.controls[name].setValue(data[name]);
    });

    console.log(this.form);
  }

That gives the following output on the console:

FormGroup
  ...
  controls: Object
    database1: FormControl
      ...
      _value: Object
      accessHost: "some host here"
      accessKey: "the key here"
....
    database2: FormControl
      ...
      _value: Object
      accessHost: "some host here"
      accessKey: "the key here"

That looks OK for so far. the html code:

<form [formGroup]="form" (ngSubmit)="onSave(form)">
  <div *ngFor="let ups of form.controls | keyVal; let i=index">
  {{ups.key}}
    <div class="form-group">
      <input class="form-control" formControlName="{{ups.key}}">
    </div>
  </div>
</form>

But this part is not working:

<input class="form-control" formControlName="{{ups.key}}">

When I check the value of {{ups.key}}, that is "database1". Is "database1" in this case not a FormControlName?

Thanks for Help

You need to bind the formControlName attribute to an expression:

<input class="form-control" [formControlName]="ups.key" />

Notice the [] arround the attribute. A good start is to take a look at this cookbook: Dynamic Form as suggested by @kcp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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