角度4:在表单中添加/删除动态输入字段

时间:2019-04-29 10:11:29

标签: angular typescript angular-reactive-forms

我在我的应用程序中使用Angular 4,在该应用程序中,我需要创建一个具有添加/删除父表单域以及基于父表单域选择的子表单域的动态表单。例如,如果我在父表单字段中选择“测试4”,则需要显示一个子表单部分,可以在其中添加/删除子表单字段。

我已经实现了动态添加/删除父表单字段的功能。但是我在子表单字段添加/删除中面临以下问题。 示例:我将为第二个父表单字段添加3个子表单字段,并且再次添加另一个父表单字段(第3个),在这里我选择“测试4”意味着我得到了以前在当前上下文中添加了3个子表单字段。

请在此处找到示例应用程序: https://stackblitz.com/edit/angular-kbudan

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, ReactiveFormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import {FormGroup, FormArray, FormBuilder} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  form: FormGroup;
  subform : FormGroup;
  public selectedField : number = 0
  public selId : string;

constructor( private fb: FormBuilder) { }

  ngOnInit() {
    this.form = this.fb.group({
      items: this.fb.array([this.createItem()])
    })

    this.subform = this.fb.group({
      subItems: this.fb.array([this.createSubItem()])
    })
  }

  //Methods for Parent form
  get formArr() {
    return this.form.get('items') as FormArray;
  }

  createItem() {
    return this.fb.group({
      dashFldName: 0,
      dataFldName: ''
    })
  }

  removeItem(index: number) {
    this.formArr.removeAt(index);
  }

  addNext() {
    //this.selectedField = 0;
    (this.form.controls['items'] as FormArray).push(this.createItem())
  }

  selField(value, index: number){
      this.selId = "subItemSec_"+index;
      alert(value)
      if(value == "test4") {
        document.getElementById(this.selId).classList.remove("d-none");
      } else {
        document.getElementById(this.selId).classList.add("d-none");
      }
  }

  submit() {
    console.log(this.form.value);
  }

  //Methods for Sub-form fields
  get subformArr() {
    return this.subform.get('subItems') as FormArray;
  }

  createSubItem() {
    return this.fb.group({
      subDashFldName: 'Success',
      subDataFldName: ''
    })
  }

  removeSubItem(index: number) {
    this.subformArr.removeAt(index);
  }

  addSubNext(index: number) {
    //"subform"+index;
    let formName = "subform"+index;
    (this.subform.controls['subItems'] as FormArray).push(this.createSubItem())
  }

}

app.component.html

<div class="card customUsersCard">
  <div class="card-body">
    <div class="colMapSec">
      <form [formGroup]="form" (ngSubmit)="submit()">
          <div  formArrayName="items"
            *ngFor="let item of form.controls['items'].controls; let i = index">
            <div [formGroupName]="i">
              <div class="row">
                <div class="col">
                    <div class="form-group">
                        <!--<input formControlName='dashFldName' type="text" class="form-control col-md-8">-->
                        <select class="form-control col-md-9" formControlName='dashFldName' #t (change)="selField(t.value,i)">
                            <option value="0" selected>Select Fields</option>
                            <option value="test1">Test 1</option>
                            <option value="test2">Test 2</option>
                            <option value="test3">Test 3</option>
                            <option value="test4">Test 4</option>
                        </select>
                    </div>
                </div>
                <div class="col">
                    <div class="form-group">
                        <input formControlName='dataFldName' type="text" class="form-control col-md-9" placeholder="Enter column name here">
                    </div>
                </div>
                <div class="col">
                    <button *ngIf="form.controls.items.controls.length > 1" type="button" (click)="removeItem(i)">Remove</button>&nbsp;
                    <button type="button" (click)="addNext()">Add Next</button>
                </div>
              </div>

             <div class="row d-none" id="subItemSec_{{i}}" style="padding: 0 16px;">
                  <form [formGroup]="subform" class="subform" style="width:100%;">
                      <div  formArrayName="subItems"
                      *ngFor="let subItem of subform.controls['subItems'].controls; let s = index">
                          <div [formGroupName]="s">
                              <div class="row">
                                  <div class="col">
                                      <div class="form-group" style="">
                                          <select class="form-control col-md-12" formControlName='subDashFldName' style="width: 70%;">
                                              <option value="Success" selected>Success</option>
                                              <option value="Failed">Failed</option>
                                          </select>
                                      </div>
                                  </div>
                                  <div class="col">
                                      <div class="form-group">
                                          <input type="text"/>
                                      </div>
                                  </div>
                                  <div class="col">
                                      <button *ngIf="subform.controls.subItems.controls.length > 1" type="button" (click)="removeSubItem(s)">-</button>&nbsp;
                                      <button type="button" (click)="addSubNext(s)">+</button>
                                  </div>
                              </div>
                          </div>
                      </div>
                  </form>
              </div>
            </div>
          </div>
        </form>
      </div>
  </div>
</div>

style.css

.d-none {
   display: none;
}

0 个答案:

没有答案