如何创建嵌套的formgroup并获取值

时间:2018-01-30 06:19:50

标签: javascript angular angular2-forms formgroups

我已经创建了一个表单,但我无法创建嵌套表单,因为我需要动态添加某些输入字段,但是现在需要的是当我单击添加链接时应添加表单嵌套。< / p>

Form image

在输入字段附近添加按钮应该只添加社交媒体链接和GitHub输入字段其他将保持不变。

HTML

<div class="container">
  <p> </p>
  <div>
      <form [formGroup]="searchForm" novalidate (ngSubmit)="submit(searchForm.value)">
          <div formArrayName="properties">
            <div *ngFor="let prop of searchForm.get('properties').controls; let i = index">
              <div class="row" [formGroupName]="i">
                  <select formControlName="desg" class="form-control">
                      <option value="CEO">CEO</option>
                      <option value="CTO">CTO</option>
                      <option value="CMO">CMO</option>
                      <option value="Project Manager">Project Manager</option>
                  </select>
                    <input formControlName="name" type="text" class="form-control" placeholder="Name">
                    <input formControlName="linkedin" type="text" class="form-control" placeholder="LinkedIn Url">
                    <input formControlName="github" type="text" class="form-control" placeholder="Github Url">
                    <button *ngIf="searchForm.controls['properties'].length > 1 " (click)="onDelProperty(i)">Delete</button>
              </div>
            </div>
          </div>
          <p>
          </p>
          <a (click)="onAddProperty()">Add</a>
          <button class="btn btn-bold btn-primary" type="submit">submit</button>
      </form>
  </div>
</div>

component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormArray, FormControl } from '@angular/forms';
import { IcoService } from '../../services/ico.service';
import { debug } from 'util';

@Component({
  selector: 'app-team',
  templateUrl: './team.component.html',
  styleUrls: ['./team.component.css']
})
export class TeamComponent implements OnInit {
  searchForm: FormGroup;
  searchForm1: FormGroup;
  constructor(private fb: FormBuilder,private icoService: IcoService,) { }

  ngOnInit() {
    this.searchForm = this.fb.group({
      properties: this.fb.array([this.createItem()])
    });    
  }

  createItem(): FormGroup {
    return this.fb.group({
      name: '',
      desg: '',
      social_media: '',
      github:''
    });
  }

  submit(formData: any) {
      this.icoService.teamDetail(formData).subscribe((result) => {
        console.log()
      }, (err) => { console.log('err',err) })
  }

  onAddProperty() {
    for(var i=1; i<=1; i++) {
      (this.searchForm.get('properties') as FormArray).push(this.createItem());
    }
  }

  onDelProperty(index:any) {
    for(var i=1; i<=1; i++) {
      (this.searchForm.get('properties') as FormArray).removeAt(index);
    }
  }

}

2 个答案:

答案 0 :(得分:0)

我不确定您的onAddPropertyonDelProperty方法中的for循环是什么。

如果我理解正确,您的namedesg控件应添加到fb.group中定义的ngOnInit。那些将只被定义一次。每次用户点击添加时,只需将createItem方法添加到您希望重复的控件。

我有类似的代码添加地址块。我的代码看起来像这样:

@Component({
    selector: 'my-signup',
    templateUrl: './app/customers/customer.component.html'
})
export class CustomerComponent implements OnInit {
    customerForm: FormGroup;

    get addresses(): FormArray{
        return <FormArray>this.customerForm.get('addresses');
    }

    constructor(private fb: FormBuilder) { }

    ngOnInit(): void {
        this.customerForm = this.fb.group({
            firstName: ['', [Validators.required, Validators.minLength(3)]],
            lastName: ['', [Validators.required, Validators.maxLength(50)]],
            addresses: this.fb.array([this.buildAddress()])
        });
    }

    addAddress(): void {
        this.addresses.push(this.buildAddress());
    }

    buildAddress(): FormGroup {
        return this.fb.group({
                addressType: 'home',
                street1: '',
                street2: '',
                city: '',
                state: '',
                zip: ''
        });
    }
 }

在上面的示例中,名字和姓氏只出现一次,但每次用户点击添加按钮时,地址字段都会重复。

有关完整的工作示例,请查看此github:https://github.com/DeborahK/Angular2-ReactiveForms(特别是Demo-Final文件夹)

更新以包含您的代码:

进行以下更改...请注意, 想要重复的所有内容都在ngOnInit中。您想要重复的所有事情都在createItem

  ngOnInit() {
    this.searchForm = this.fb.group({
      name: '',
      desg: '',
      properties: this.fb.array([this.createItem()])
    });    
  }

  createItem(): FormGroup {
    return this.fb.group({
      social_media: '',
      github:''
    });
  }

当然,您还需要从html中的ngFor中删除不想重复的字段。只需将它们移到ngFor上方。

答案 1 :(得分:0)

您可以尝试以下操作,这可能对您有所帮助:

&#13;
&#13;
import { ToasterContainerComponent, ToasterService, ToasterConfig} from 'angular2-toaster';
// ======================== Internal Dependency Module Loading Start ================================
import {TabViewModule} from 'primeng/tabview';

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators,FormArray, FormControl} from '@angular/forms';
import { Router } from '@angular/router';

import { GlobalAjaxMethodHandler } from '../util/GlobalAjaxMethodHandler';
import { GlobalValidationService } from '../util/GlobalValidationService';
import { AjaxMethodName } from '../util/GlobalAjaxPathHandler';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;	

  form = new FormGroup({
    cities: new FormArray([
      // new FormControl('drp')
      this.initAddress()
    ]),
  });

  constructor(public _fb: FormBuilder,   private _GlobalAjaxMethodHandler: GlobalAjaxMethodHandler, public router: Router,public _toasterService:ToasterService) { }

  ngOnInit() {
  	this.formIntialization();
  }

  initAddress() {
        // initialize our address
        return this._fb.group({
            third  : ['', Validators.required],
            second: [''],
            first: [''],
            four: ['']
        });
    }


  //================================= Initialize form Value ============================================
    formIntialization() {
      this.loginForm = this._fb.group ({
        Email : ['', [Validators.required, GlobalValidationService.emailValidator]],
        Password : ['', [Validators.required, GlobalValidationService.passwordValidator]]
      });
    }

     get cities(): FormArray { return this.form.get('cities') as FormArray; }

    addCity() { 
      this.cities.push(this._fb.group({
            third  : ['', Validators.required],
            second: [''],
            first: [''],
            four: ['']
        }));
    }

    onSubmit() {
      console.log(this.cities.value);  // ['SF', 'NY']
      console.log(this.form.value);    // { cities: ['SF', 'NY'] }
    }

    setPreset() { 
      if(this.cities.length > 1){
       this.cities.removeAt(this.cities.length-1); 
      }
    }

}
&#13;
 <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <div formArrayName="cities">
             <!-- <div *ngFor="let city of cities.controls; index as i">
                  <input [formControlName]="i" placeholder="City">
                </div> -->

             <div *ngFor="let city of cities.controls; index as i">
                    <div [formGroupName]="i">
                        <select formControlName="first">
                            <option [selected]="true">--Select--</option>
                            <option>A1</option>
                            <option>B1</option>
                            <option>C1</option>
                        </select>

                        <select formControlName="second">
                            <option [selected]="true">--Select--</option>
                            <option>A2</option>
                            <option>B2</option>
                            <option>C2</option>
                        </select>

                        IN : <input type="checkbox" formControlName="third" value="+">
                        Out :<input type="checkbox" formControlName="four" value="+">
                 </div>
         </div>
        </div>
        <input type="button" name="" value="Enable integration" (click)="onSubmit()">
</form>
&#13;
&#13;
&#13;