如何在angular2中添加嵌套表单

时间:2018-01-30 12:12:30

标签: angular angular2-template angular-forms formgroups

Image contains problem

我创建了一个表单,它是从添加按钮动态添加行但我还创建了一个按钮,我只需要从该链接添加一些组件。添加更多链接按钮用于仅创建这两个组件。

我使用嵌套表单方法,动态表单方法但不能做同样的事情。需要帮助。

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 [formGroupName]="i" class="row col-md-12">
                  <select formControlName="desg" class="form-control col-md-2">
                      <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 col-md-3" placeholder="Name">
                  <select formControlName="socialMediaCategory" class="form-control col-md-2">
                        <option value="LinkedIn">LinkedIn</option>
                        <option value="Facebook">Facebook</option>
                        <option value="Twitter">Twitter</option>
                        <option value="Github">Github</option>
                  </select>
                  <input formControlName="link" type="text" class="form-control col-md-3" placeholder="Link">
                  <a class="col-md-2" (click)="onAddProperty()">Add More Links</a>
                  <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>

成分: -

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: '',
      socialMediaCategory: '',
      link: ''
  }

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

}

1 个答案:

答案 0 :(得分:0)

您应该将searchForm扩展一个属性,例如:FormArray类型的socialMediaLinks

createItem(): FormGroup {
    return this.fb.group({
      name: '',
      desg: '',
      socialMediaLinks: this.fb.array([this.createSocialMediaItem()])
    });
  }

现在创建用于创建FormGroup的函数,其中包含socialMediaLinks FormArray的项目(socialMediaCategory,link):

createSocialMediaItem(): FormGroup {
    return this.fb.group({
      socialMediaCategory: '',
      link: ''
    });
  }

添加两个函数以添加新项目并从socialMediaLinks FormArray中删除项目:

onAddSocialMediaLink(linkForm: FormGroup) {
    (linkForm.get('socialMediaLinks') as FormArray).push(this.createSocialMediaItem());
}

onDelSocialMediaLink(linkForm: FormGroup, index: any) {
  (linkForm.get('socialMediaLinks') as FormArray).removeAt(index);
}

在这里你可以看到,这个函数需要一个FormGroup类型的变量作为参数。这需要您访问FormArray。在这里,您应该在模板中prop的迭代中提供searchForm.get('properties').controls

以下是扩展模板:

    <form [formGroup]="searchForm" novalidate (ngSubmit)="submit(searchForm.value)">
          <div formArrayName="properties">
            <div *ngFor="let prop of searchForm.get('properties').controls; let i = index">
              <div [formGroupName]="i" class="row col-md-12">
                  <select formControlName="desg" class="form-control col-md-2">
                      <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 col-md-3" placeholder="Name">
                  <div formArrayName="socialMediaLinks">
                    <div *ngFor="let links of prop.get('socialMediaLinks').controls; let j = index">
                      <div [formGroupName]="j" class="row col-md-12">
                        <select formControlName="socialMediaCategory" class="form-control col-md-2">
                          <option value="LinkedIn">LinkedIn</option>
                          <option value="Facebook">Facebook</option>
                          <option value="Twitter">Twitter</option>
                          <option value="Github">Github</option>
                        </select>
                        <input formControlName="link" type="text" class="form-control col-md-3" placeholder="Link">
                        <a class="col-md-2" (click)="onAddSocialMediaLink(prop)">Add More Links</a>
                        <button *ngIf="prop.controls['socialMediaLinks'].length > 1 " (click)="onDelSocialMediaLink(prop, j)">Delete</button>
                      </div>
                    </div>
                  </div>                  
              </div>
            </div>
          </div>
          <p>
          </p>
          <button *ngIf="searchForm.controls['properties'].length > 1 " (click)="onDelProperty(i)">Delete</button>
          <a (click)="onAddProperty()">Add</a>
          <button class="btn btn-bold btn-primary" type="submit">submit</button>
      </form>

在stackblitz上查看我的工作example