如何在 FormArray 中设置 FormControl 的值

how to set value of FormControl inside FormArray

我目前有一个使用 Angular 5 的项目,我是这个 angular 概念的新手。

我有一个组件,用户可以在其中选择他们想要使用的模块...模块的界面如下:

export interface ModuleComponent{
    id: number;
    moduleName: string;
    level: number;
    parentId: number;
    displayOrder: number;
    children: ModuleComponent[];
}

它自引用 object parent 和 children。在这里,我只想让用户访问 children 模块组件……而不是父节点。

我的 form.component.ts 像这样:

import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder, FormArray } from '@angular/forms';
import { Router, ActivatedRoute } from '@angular/router';
import { AlertifyService } from './../../_services/alertify.service';
import { UserGroup } from './../../_models/usergroup';
import { ModuleComponent } from './../../_models/moduleComponent';
import { UserGroupService } from './../../_services/userGroup.service';
import { environment} from './../../../environments/environment';

@Component({
  selector: 'app-form-usergroup',
  templateUrl: './form-usergroup.component.html',
  styleUrls: ['./form-usergroup.component.css']
})
export class FormUserGroupComponent implements OnInit {
    @Input() ug: UserGroup;
    @Input() moduleComponents: ModuleComponent[];
    @Input() buttonName: string; 
    @Output() onSubmit = new EventEmitter<any>();
    editForm: FormGroup;

  constructor(private ugService: UserGroupService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private alertify: AlertifyService) { 


    }

  ngOnInit() {
      this.createForm();
  }

  createForm() {
      this.editForm = this.fb.group({
          groupName: [this.ug.groupName, Validators.required],
          details : this.fb.array([])
      });

      this.setDetails(this.moduleComponents);
  }

  get details(): FormArray {
      return this.editForm.get('details') as FormArray ;
  }


  setDetails(details: ModuleComponent[]) {
    let arr = [] ; 
    details.forEach(dt => {
        if(dt.children){
            dt.children.forEach(x => {
                let fc = new FormControl();
                if(this.ug.details.includes(x.id))
                {
                    fc.setValue(true);
                }
                arr.push(fc);
            });
        }
    });
    const arrFR = this.fb.array(arr);
    this.editForm.setControl('details', arrFR);
  }
}

来自 parent 组件的输入有这样的数据:

this.ug = {
 'groupName' : 'Module List'
 'details': [1,2,3,4,7,9,10] ; // these are id of selected modules  
}

现在我的 html 喜欢:

import {
  Component,
  OnInit,
  Input,
  EventEmitter,
  Output
} from '@angular/core';
import {
  FormGroup,
  FormControl,
  Validators,
  FormBuilder,
  FormArray
} from '@angular/forms';
import {
  Router,
  ActivatedRoute
} from '@angular/router';
import {
  AlertifyService
} from './../../_services/alertify.service';
import {
  UserGroup
} from './../../_models/usergroup';
import {
  ModuleComponent
} from './../../_models/moduleComponent';
import {
  UserGroupService
} from './../../_services/userGroup.service';
import {
  environment
} from './../../../environments/environment';

@Component({
  selector: 'app-form-usergroup',
  templateUrl: './form-usergroup.component.html',
  styleUrls: ['./form-usergroup.component.css']
})
export class FormUserGroupComponent implements OnInit {
  @Input() ug: UserGroup;
  @Input() moduleComponents: ModuleComponent[];
  @Input() buttonName: string;
  @Output() onSubmit = new EventEmitter < any > ();
  editForm: FormGroup;

  constructor(private ugService: UserGroupService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private alertify: AlertifyService) {


  }

  ngOnInit() {
    this.createForm();
  }

  createForm() {
    this.editForm = this.fb.group({
      groupName: [this.ug.groupName, Validators.required],
      details: this.fb.array([])
    });

    this.setDetails(this.moduleComponents);
  }

  get details(): FormArray {
    return this.editForm.get('details') as FormArray;
  }


  setDetails(details: ModuleComponent[]) {
    let arr = [];
    details.forEach(dt => {
      if (dt.children) {
        dt.children.forEach(x => {
          let fc = new FormControl();
          if (this.ug.details.includes(x.id)) {
            fc.setValue(true);
          }
          arr.push(fc);
        });
      }
    });
    const arrFR = this.fb.array(arr);
    this.editForm.setControl('details', arrFR);
  }

}
<div class="container">
  <div class="row">
    <form [formGroup]="editForm" class="form-horizontal">
      <div class="panel panel-info">
        <div class="panel-heading">
          <h3 class="panel-title">User Group</h3>
        </div>
        <div class="panel-body">
          <div class="form-group required" [ngClass]="{'has-error': editForm.get('groupName').touched && editForm.get('groupName').hasError('required')}">
            <label for="groupName" class="col-sm-2">User Group Name</label>
            <div class="col-sm-7">
              <input type="text" class="form-control" placeholder="Group Name" formControlName="groupName">
              <span class="help-block" *ngIf="editForm.get('groupName').touched && editForm.get('groupName').hasError('required')">Group Name is required</span>
            </div>
          </div>
          <div class="panel-body">
            <tabset>
              <tab *ngFor="let mod of moduleComponents" heading="{{mod.moduleName}}">
                <div class="row">
                  <div class="col-sm-4" *ngFor="let child of mod.children; let i = index">
                    <input type="checkbox"> {{child.moduleName}} {{child.id}}
                  </div>
                </div>
              </tab>
            </tabset>
          </div>
        </div>
      </div>
    </form>
  </div>
</div>

如您所见,我还没有将 FormArray 放入我的 html,我仍然不知道如何为复选框放置 FormControl。请告诉我该怎么做。

让我进一步解释,我希望我能拥有这个:

好的,我将解释该代码背后的逻辑以及我的预期。在 php / plain html 中,我希望我可以创建许多这样的复选框

<input type="checkbox" name="details[]" value="1"> Module 1
<input type="checkbox" name="details[]" value="2"> Module 2
<input type="checkbox" name="details[]" value="3"> Module 3
<input type="checkbox" name="details[]" value="4"> Module 4 
.......
<input type="checkbox" name="details[]" value="20"> Module 20

所以当提交时它会 return 详细信息[1,2,5,6] => 选中复选框的地方。

我不知道你试图在 setDetails 函数中实现的逻辑,但根据我的理解,下面是将控件添加到 formArray 并使用值对其进行初始化并在需要时放置验证器的逻辑:

setDetails(details: ModuleComponent[]) {
    let arr = [] ; 
    details.forEach(dt => {
        if(dt.children){
            dt.children.forEach(x => {
                this.editForm.controls['details'].push(this.fb.group({
                 'id': [x.id, Validaors.required],
                  'pass': [x.pass, Validaors.required]
             }))
            });
        }
    });

  }

希望我能帮上忙?如果我能提供进一步帮助,请告诉我。

我认为您需要在 html 上为您的复选框控件声明 formgroup,像这样(不确定您是否需要 formArray 或 formGroup):

<div class="panel-body" formArrayName="details">

<div class="panel-body" formGroupName="details">