如何在 FormArray 中设置 FormControl 的值

Posted

技术标签:

【中文标题】如何在 FormArray 中设置 FormControl 的值【英文标题】:how to set value of FormControl inside FormArray 【发布时间】:2018-12-03 13:46:09 【问题描述】:

我目前有一个使用 Angular 5 的项目,我对这个 Angular 概念很陌生。

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

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

它自引用对象的父对象和子对象。在这里,我只希望用户访问子模块组件……而不是父级。

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

从父组件输入有这样的数据:

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

所以当提交时它会返回 details[1,2,5,6] => 勾选复选框。

【问题讨论】:

我想我无法得到这个问题的答案。所以我为复选框创建了“手动”值。 我使用的解决方案:codepen.io/anon/pen/VdEMvQ 【参考方案1】:

我不知道您尝试在 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]
             ))
            );
        
    );

  

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

【讨论】:

我刚刚编辑了我的问题并在最后一行进行了解释。谢谢。 似乎出现了类似的问题。请访问以下链接:***.com/questions/40927167/…【参考方案2】:

我认为您需要在您的 html 中为您的复选框控件声明 formgroup,如下所示(不确定您是否需要 formArray 或 formGroup):

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

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

【讨论】:

以上是关于如何在 FormArray 中设置 FormControl 的值的主要内容,如果未能解决你的问题,请参考以下文章

为什么未在formarray自定义验证值更改中设置错误

Mat Table 中的嵌套反应表单找不到控件

FormArray嵌套在另一个FormArray中时如何获取FormArrayName?

如何在 Netbeans 中设置环境变量?

如何在 Android 中设置 libsvm?

如何在 Laravel 中设置全局变量?