javascript - 如何在 Angular2 中迭代表单生成器?

标签 javascript angular typescript

我尝试迭代表单控件,但遇到一些问题。我使用 Angular2 中的 FormBuilder。

我的 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);
  }

这会在控制台上提供以下输出:

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"

到目前为止看起来还不错。 html代码:

<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>

但这部分不起作用:

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

当我检查 {{ups.key}} 的值时,它是“database1”。在这种情况下,“database1”不是 FormControlName 吗?

感谢您的帮助

最佳答案

您需要将 formControlName 属性绑定(bind)到表达式:

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

注意属性周围的 []。 一个好的开始是看一下这本食谱:Dynamic Form正如@kcp建议的

关于javascript - 如何在 Angular2 中迭代表单生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41998331/

相关文章:

javascript - 未捕获的类型错误 : Cannot read property 'innerHTML' of null

html - 我可以从我的组件 .css 文件中设置我的 ngx-bootstrap 元素的样式吗?

Angular2 @ngrx/store/effects - 在哪里调用服务函数

reactjs - 如何为浏览器编译 typescript

javascript - Chrome 开发者工具未显示带有请求 header 的 xhr 大小

javascript - typescript :使用外部声明的变量

php - 我想在下拉列表中添加表结构

javascript - 为什么在 Angular 2 中,事件属性在括号中?

javascript - 取消 Angular 形式时撤消对模型状态的更改

javascript - 需要在 typescript 中为以 "abcd_"开头的字符串编写正则表达式,并且仅允许字母数字字符和下划线