如何在angular中实现动态复选框

时间:2019-04-24 16:41:17

标签: angular angular6 angular-reactive-forms dynamic-forms

我正在尝试为我的角度应用程序实现动态形式,并且我遵循https://angular.io/guide/dynamic-form

我有一个复选框问题,其中有4个以上的复选框选项。

到目前为止,我的复选框问题模型类似于仅具有一个formControllerName(“ fruits_key”)的下拉列表

export class CheckBoxQuestion extends QuestionBase<string> {
  controlType = "checkbox";
  options: {key: string, value: string}[] = [];

  constructor(options: {} = {}) {
    super(options);
    this.options = options["options"] || [];
 }

我的对象是

new CheckBoxQuestion({
            key: "fruits_key",
            label: "Choose Fruits",
            options: [
              { key: "Apple", value: true },
              { key: "Orange", value: false },
              { key: "Grapes", value: false },
              { key: "Banana", value: false }
            ]
          })

这是我的HTML,用于显示复选框项目

<ng-container *ngSwitchCase="'checkbox'">
      <div class="d-flex">
        <div class="custom-control custom-checkbox" *ngFor="let opt of question['options']; index as idx">
          <input type="checkbox" class="custom-control-input" [formControlName]="question.key"
            [checked]="opt.value" ">
          <label class="custom-control-label">{{opt.key}}</label>
        </div>
      </div>
    </ng-container>

Q)[formControlName]出现了问题,对于所有复选框项目,它都设置为相同。如何正确实现复选框项目,是否需要重写复选框模型?请告知您是否有更好的解决方案。

角度站点演示:https://angular.io/generated/live-examples/dynamic-form/stackblitz.html

1 个答案:

答案 0 :(得分:0)

我自己找到了解决方案。

<ng-container *ngSwitchCase="'checkbox'">
        <div class="d-flex">
          <div *ngFor="let option of question['options']; let i=index" [formArrayName]="question.key" class="custom-control custom-checkbox">
            <input type="checkbox" [formControlName]="i" id="{{question.key +'_'+ option.key}}" class="custom-control-input" (change)="getUpdate(question)"/>
            <label for="{{question.key +'_'+ option.key}}" class="custom-control-label">{{option.key}}</label>
          </div>
        </div>
 </ng-container>

和我的问题控制服务,该服务将模型转换为表单组/表单控件/表单数组。

@Injectable()
export class QuestionControlService {
constructor() {}

toFormGroup(questions: QuestionBase<any>[]) {
let group: any = {};

questions.forEach(question => {
  if (question.controlType === "checkbox") {
    group[question.key] = this.buildCheckBoxArray(question["options"]);
  } else {
    group[question.key] = question.required
      ? new FormControl(question.value || "", Validators.required)
      : new FormControl(question.value || "");
  }
});
return new FormGroup(group);
}

buildCheckBoxArray(itemsArr): any {
 const arr = itemsArr.map(item => {
   return new FormControl(item.value);
 });
 return new FormArray(arr);
}
}