如何在FormArray中设置FormControl的值

时间:2018-06-25 02:57:24

标签: angular typescript angular5 angular-reactive-forms

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

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

target_arr = np.random.rand(32, 100, 4)
query_arr = np.random.rand(32, 20, 4)

match_model_scores = np.array([
    match_model.predict([target_arr[:, t:t + 20, :], query_arr])
    for t in range(81)
])
scores = model.predict([target_arr, query_arr])

print(np.allclose(scores, match_model_scores.max(axis=0)))
True

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

我的form.component.ts像这样:

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

从父组件输入的数据如下:

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

现在我的html就像:

this.ug = {
 'groupName' : 'Module List'
 'details': [1,2,3,4,7,9,10] ; // these are id of selected modules  
}
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);
  }

}

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

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

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

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

因此,提交后它将返回详细信息[1,2,5,6] =>其中选中了复选框。

2 个答案:

答案 0 :(得分: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]
             }))
            });
        }
    });

  }

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

答案 1 :(得分:1)

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

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

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