0

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

表格图像

输入字段附近的添加按钮应仅添加社交媒体链接,而 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>

组件.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);
    }
  }

}
4

2 回答 2

0

我不确定您的 for 循环在您的onAddPropertyandonDelProperty方法中的用途。

如果我理解正确,您的和name控件desg应该添加到. 然后将只定义一次。仅将您希望在每次用户单击添加时重复的控件添加到方法中。fb.groupngOnInitcreateItem

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

@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:''
    });
  }

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

于 2018-01-30T06:33:51.507 回答
0

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

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

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

于 2018-01-30T08:08:14.800 回答