【问题标题】:Reactive Forms Angular 6反应形式Angular 6
【发布时间】:2019-02-18 20:48:53
【问题描述】:

我是 Angular 6 的新手。

这是我面临一些问题的表单的 html 标记

<form [formGroup]="detailsForm">
    <div class="row parent-row" *ngFor="let row of formData;">
        <input class="input-lg parent-input-primary" placeholder="{{row.first }} formControlName ={{row.first}}" />
        <input class="input-lg parent-input-secondary" placeholder="{{row.second }} formControlName ={{row.second}}" />
    </div>
</form>

formData 是 Json 类型的对象:

formData: any[] = [
    {
        first: 'business-name',
        second: 'business-type',

    },
    {
        first: 'contact-mobile',
        second: 'purpose',
    }
]

这里的 first 和 second 是动态字符串,并且在整个表单中都是唯一的。 我需要使用类似这样的角度反应表单模块来初始化表单:

    detaislForm = FormGroup;
    this.detailsForm = new FormGroup({
        //here I need to write something to init FormControl here, so that angular knows formControls by first and second variables of FormData 
     }
    );

您能建议我通过这种方法在 formGroup 中插入表单控件吗?

【问题讨论】:

标签: angular


【解决方案1】:

在这里使用表单数组:

参考--->https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays

STACKBLITZ DEMO

TS:

formData: any[] = [
    {
      first: 'business-name',
      second: 'business-type',

    },
    {
      first: 'contact-mobile',
      second: 'purpose',
    }
  ]
  detailsForm: FormGroup;

  constructor(private _fb: FormBuilder) {

  }
  ngOnInit() {

    this.detailsForm = this._fb.group({
      formData: this._fb.array([])
    });

    for (let data of this.formData) {
      this.addValue(data);
    }
  }
  createFormArray(data) {
    return this._fb.group({
      first: data.first,
      second: data.second
    })
  }

  addValue(data) {
    this.getData().push(this.createFormArray(data));
  }
  getData() {
    return this.detailsForm.controls.formData as FormArray
  }

HTML:

<form [formGroup]="detailsForm">
    <div formArrayName="formData">
        <div *ngFor="let row of detailsForm.get('formData').controls; let i = index;" [formGroupName]="i">
            <input class="input-lg parent-input-primary" placeholder="first" formControlName="first" />
            <input class="input-lg parent-input-secondary" placeholder="second" formControlName="second" />
        </div>
    </div>
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2018-10-26
    • 1970-01-01
    • 2018-11-30
    • 2019-01-06
    • 1970-01-01
    相关资源
    最近更新 更多