代码之家  ›  专栏  ›  技术社区  ›  nightingale2k1

如何在窗体数组中设置窗体控件的值

  •  1
  • nightingale2k1  · 技术社区  · 6 年前

    我有一个组件,用户可以在其中选择要使用的模块…模块具有如下接口:

    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>

    让我进一步解释一下,我希望我能得到:

    <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

    2 回复  |  直到 6 年前
        1
  •  1
  •   anas husain    6 年前

    我不知道您试图在setdetails函数内部实现的逻辑,但根据我的理解,下面是将控件添加到formaray并用值初始化该控件以及在需要时放置验证器的逻辑:

    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]
                 }))
                });
            }
        });
    
      }
    

        2
  •  1
  •   chinaski    6 年前

    我认为您需要在HTML中为复选框控件声明FormGroup,如下所示(不确定您是否需要FormArray或FormGroup):

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

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