angular - 如何在 FormArray 中设置 FormControl 的值

标签 angular typescript angular5 angular-reactive-forms

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

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

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

它自引用对象父项和子项。在这里,我只想让用户访问子模块组件……而不是 parent 。

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

所以当提交时它会返回详细信息[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]
             }))
            });
        }
    });

  }

希望我能帮上忙?让我知道是否可以提供进一步的帮助。

关于angular - 如何在 FormArray 中设置 FormControl 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51015757/

相关文章:

angular - Http 提供商错误 Ionic 3

angular - 如何从单元测试访问注入(inject)的 ngControl?

typescript - 无法将已编译的 JS 文件映射到 Electron 的 browserWindow 中的源 TS 文件

javascript - 在 Typescript 中使用保留关键字作为类/实例的方法

angular - 将链接 amphtml 附加到 angular 应用程序中

javascript - 如何在angular 5中以编程方式转换html元素

angular - 使用 primeNG 和 dataTable 进行 CSV 导出的嵌套 json 对象

typescript - 如何迭代 Angular 2 ng-content 项目?

angular - 如何动态添加和删除 Angular 5 中的表行和列?

javascript - 在 Angular 组件中获取 <html> 标签