如何在angular2中添加嵌套形式 [英] how to add nested forms in angular2

查看:73
本文介绍了如何在angular2中添加嵌套形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

图片包含问题

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

I have created a form and it is adding rows dynamically from add button but i have also created a button from which i need to add only some components from that link.Add more link button is used to create only those two components.

我曾经使用过嵌套表格方法,动态表格方法,但无法做到这一点.需要帮助.

i have used nested form approach, dynamic form approach but not able to do the same. Help needed.

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

}

推荐答案

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

You should extend your searchForm by one more property for example: socialMediaLinks of type FormArray:

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

现在创建函数,用于为带有socialMediaLinks FormArray的项(socialMediaCategory,链接)创建FormGroup:

Now create function for creating FormGroup with items (socialMediaCategory, link) for socialMediaLinks FormArray:

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

添加两个功能以添加新项并从socialMediaLinks FormArray删除项:

Add two function for add new item and delete an item to/from the 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.在这里,您应该通过迭代模板中的searchForm.get('properties').controls给出prop.

Here you can see, that this function need an variable of type FormGroup as parameter. This need you for access to the FormArray. Here you should give prop from iterating of searchForm.get('properties').controls in template.

以下是该模板的扩展模板:

Here is extended template for that:

    <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上查看我的工作示例.

Check my working example on stackblitz.

这篇关于如何在angular2中添加嵌套形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆