Angular8 ngfor FormControl

时间:2019-10-09 10:22:12

标签: angular

如何将mat-option绑定到control?我尝试了类似<mat-option *ngFor="let option of control.value" [value]="option"><mat-option *ngFor="let option of control.value['option']" [value]="option">和其他变体的方法。但仍然无法正常工作。

HTML

<form [formGroup]="myForm">
  <ng-container *ngFor="let control of myForm.controls | keyvalue">
    <mat-form-field>
      <mat-select formControlName="{{control.key}}">
        <mat-option *ngFor="let option of options" [value]="option">
          {{option.parameter}}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </ng-container>
</form>

TS

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  options = [{ type: "first", parameter: "first" }, { type: "first", parameter: "first" }];
  secondOptions = [{ type: "second", parameter: "second " }, { type: "second", parameter: "second" }];
  myForm = new FormGroup({
    first: new FormControl(this.options),
    second: new FormControl(this.secondOptions)
  });

  constructor() {
    this.myForm.controls
  }
}

2 个答案:

答案 0 :(得分:1)

将选项保留在FormControl之外,不要将选项设置为值,您需要处理控件外部的选项。

HTML:

<form [formGroup]="myForm">
  <ng-container *ngFor="let control of myForm.controls | keyvalue">
    <mat-form-field>
      <mat-select formControlName="{{control.key}}">
        <mat-option *ngFor="let option of options[control.key]" [value]="option">
          {{option.parameter}}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </ng-container>
</form>

TS。请注意,我们创建了一个选项对象,其属性名称与控件的名称相同

options = {
    first:  [
      { type: "first", parameter: "first" }, { type: "first", parameter: "first" }
    ],
    second: [
      { type: "second", parameter: "second " },
      { type: "second", parameter: "second" }
    ]
  }
  myForm = new FormGroup({
    first: new FormControl(),
    second: new FormControl()
  });

  constructor() {
    this.myForm.controls
  }

Demo

答案 1 :(得分:0)

在我的评论之后,您不应将选项绑定到表单控件。

相反,只需创建一个二维数组,如下所示:

groups = [
  { controlName: 'first', options : [{ type: "first", parameter: "first" }, { type: "first", parameter: "first" }] },
  { controlName: 'second', options : [{ type: "second", parameter: "second " }, { type: "second", parameter: "second" }] },
];

myForm = new FormGroup({
  first: new FormControl(),
  second: new FormControl()
});

并对其进行迭代。

<form [formGroup]="myForm">
  <ng-container *ngFor="let obj of groups">
    <mat-form-field>
      <mat-select [formControlName]="obj.controlName">
        <mat-option *ngFor="let option of obj.options | keyvalue" [value]="option">
          {{ keyval.parameter }}
        </mat-option>
      </mat-select>
    </mat-form-field>
  </ng-container>
</form>