如何在角度2中制作动态表单

时间:2017-03-27 00:48:45

标签: angular typescript angular2-forms

我正在使用angular2,我需要制作一个动态表单,问题是在发送表单时只捕获最后一个输入元素。我知道我需要将此元素转换为一种安排,但我没有成功enter image description here

enter image description here

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { InformeService } from './informe.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
declare var jQuery: any;
declare var $: any;

@Component({
  selector: 'app-informe',
  templateUrl: './informe.component.html',
  styleUrls: ['./informe.component.css'],
  providers: [InformeService]
})
export class InformeComponent implements OnInit {

  objGeneralIndex: number = 1;
  objGeneral = [{ id: 1, text: "" }];
  objEspecificos = [{ id: 1, text: "" }];
  objEspecificosIndex: number = 1;

  formInforme: FormGroup;

  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private service: InformeService,
    private fb: FormBuilder
  ) { this.crearControles(); }

  ngOnInit() { $("#infoBasic").show(500); $("#objGeneral").hide(500); $("#objEspec").hide(500); }
  showInfoBasic() {
    $("#infoBasic").show(500); $("#objGeneral").hide(500); $("#objEspec").hide(500);
  }
  showObjGral() {
    $("#infoBasic").hide(500); $("#objGeneral").show(500); $("#objEspec").hide(500);
  }
  showObjEspec() {
    $("#infoBasic").hide(500); $("#objGeneral").hide(500); $("#objEspec").show(500);
  }

  crearControles() {
    this.formInforme = this.fb.group({
      tituloInforme: '',
      fechaInforme: '',
      objetivoGeneral: [{ id: 1, text: "" }],
      objEspec: Array
    })
  }

  guardarInforme() {
    this.service.addInforme(this.formInforme.value)
      .subscribe(
      rt => console.log(rt),
      er => console.log(er),
      () => console.log('Terminado')
      );
  }

  addObjetivo(): void {
    this.objGeneralIndex++;
    this.objGeneral.push({ id: this.objGeneralIndex, text: "" });
  }
  delObjGral(obj): void {
    for (var i = 0; i < this.objGeneral.length; i++) {
      if (this.objGeneral[i].id == obj.id) {
        this.objGeneral.splice(i, 1);
      }
    }
  }

  addObjectivoEspecifico(): void {
    this.objEspecificosIndex++;
    this.objEspecificos.push({ id: this.objEspecificosIndex, text: "" });
  }

  delObjEspecifico(obj): void {
    for (var i = 0; i < this.objEspecificos.length; i++) {
      if (this.objEspecificos[i].id == obj.id) {
        this.objEspecificos.splice(i, 1);
      }
    }
  }
}
/* DivTable.com */
.divTable{
	display: table;
	width: 100%;
}
.divTableRow {
	display: table-row;
}
.divTableHeading {
	background-color: #EEE;
	display: table-header-group;
}
.divTableCell, .divTableHead {
	text-align: center;
	border: 1px solid #999999;
	display: table-cell;
	padding: 3px 10px;
}
.divTableHeading {
	background-color: #EEE;
	display: table-header-group;
	font-weight: bold;
}
.divTableFoot {
	background-color: #EEE;
	display: table-footer-group;
	font-weight: bold;
}
.divTableBody {
	display: table-row-group;
}

button#addObjetivo, #addObjetivoEspec{
    float: right;
    margin-top:-60px;
}
button#btn_sent {
    float: right;
    margin-top: -81px;
    margin-right: 12%;
}
#control-buttons{
    float: right;
    margin-top:-50px;
}
#dellCell{
    width:5%;
}
#bodyInforme {
	width: 90%;
	margin-left: auto;
	margin-right: auto;
}
#panelInforme {
	height: 480px;
}
#overflowGral, #overflowEspec{
	height: 300px;
	overflow: auto;
}
<div class="container">
  <div id="panelInforme" class="panel panel-default">
    <div id="bodyInforme" class="panel-body">
      <h3>Formulario Creación - Informe de Gestion</h3>
      <div id="control-buttons">
        <button (click)="showInfoBasic()" id="btn_general" type="button" class="btn btn-info">1</button>
        <button (click)="showObjGral()" id="btn_especifico" type="button" class="btn btn-info">2</button>
        <button (click)="showObjEspec()" id="btn_especifico" type="button" class="btn btn-info">3</button>
      </div><hr>
      <form novalidate [formGroup]="formInforme">
        <button id="btn_sent" (click)="guardarInforme()" type="submit" class="btn btn-success">Enviar Informe</button>
        <div id="infoBasic">
          <h4>Información Básica</h4>
          <hr>
          <div class="form-group">
            <label for="tituloInforme">Titulo de Informe</label>
            <input id="tituloInforme" formControlName="tituloInforme" type="text" class="form-control" placeholder="Titulo de Informe">
          </div>
          <div class="form-group">
            <label for="fechaInforme">Fecha:</label>
            <input id="fechaInforme" formControlName="fechaInforme" type="text" class="form-control">
          </div>
        </div>
        <div id="objGeneral">
          <div id="objGral" class="form-group">
            <h4>Ingrese Objetivos Generales</h4>
            <hr>
            <button (click)="addObjetivo()" id="addObjetivo" type="button" class="btn btn-success">Agregar Fila</button>
            <div id="overflowGral">
              <div class="divTable">
                <div class="divTableBody">
                  <div class="divTableRow">
                    <div class="divTableCell">#</div>
                    <div class="divTableCell">Puntos</div>
                  </div>
                  <div *ngFor="let obj of objGeneral; let i = index;" id="tbl_objGeneral" class="divTableRow">
                    <div class="divTableCell">{{ (i+1) }}</div>
                    <div class="divTableCell">
                      <input id="objetivoGeneral" formControlName="objetivoGeneral" class="form-control" value="{{ obj.text }}" type="text" placeholder="Objetivo General">
                    </div>
                    <div class="divTableCell" id="dellCell">
                      <button (click)="delObjGral(obj)" type="button" class="btn btn-danger">Eliminar</button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div id="objEspec" class="form-group">
          <h4>Ingrese Objetivos Específicos</h4>
          <hr>
          <button (click)="addObjectivoEspecifico()" id="addObjetivoEspec" type="button" class="btn btn-success">Agregar Fila</button>
          <div id="tbl_espec" class="divTable">
            <div id="overflowGral">
              <div class="divTableBody">
                <div class="divTableRow">
                  <div class="divTableCell">#</div>
                  <div class="divTableCell">Puntos</div>
                </div>
                <div *ngFor="let obj of objEspecificos; let i = index;" id="tbl_objGeneral" class="divTableRow">
                  <div class="divTableCell">{{ (i+1) }}</div>
                  <div class="divTableCell">
                    <input id="objEspec" formControlName="objEspec" class="form-control" value="{{ obj.text }}" type="text" placeholder="Ingrese Objetivos Específicos">
                  </div>
                  <div class="divTableCell" id="dellCell">
                    <button (click)="delObjEspecifico(obj)" type="button" class="btn btn-danger">Eliminar</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

我怀疑您应该为FormArrayobjetivoGeneral字段使用objEspec课程:

this.formInforme = this.fb.group({
  tituloInforme: '',
  fechaInforme: '',
  objetivoGeneral: this.fb.array([this.initObjetivo()]),
  objEspec: this.fb.array([this.initObjEspec()])
})

initObjetivo() {
  return this.fb.group({ id: this.objGeneralIndex++, text: "" });
}

addObjetivo(): void {
  const objetivoArray = <FormArray>this.formInforme.controls['objetivoGeneral'];
  const newObjetivo = this.initObjetivo();

  objetivoArray.push(newObjetivo);
}
delObjGral(idx: number): void {
  const objetivoArray = <FormArray>this.formInforme.controls['objetivoGeneral'];
  objetivoArray.removeAt(idx);
} 

initObjEspec() {
  return this.fb.group({ id: this.objEspecificosIndex++, text: "" });
}

addObjectivoEspecifico(): void {
  const objEspecArray = <FormArray>this.formInforme.controls['objEspec'];
  const newobjEspec = this.initObjEspec();

  objEspecArray.push(newobjEspec);
}

delObjEspecifico(idx: number): void {
  const objEspecArray = <FormArray>this.formInforme.controls['objEspec'];
  objEspecArray.removeAt(idx);
}

以下是objetivoGeneral标记

的示例视图
<div id="overflowGral" formArrayName="objetivoGeneral">
  <div class="divTable">
     <div class="divTableBody">
        <div class="divTableRow">
          <div class="divTableCell">#</div>
          <div class="divTableCell">Puntos</div>
         </div>
        <div [formGroupName]="i" *ngFor="let obj of formInforme.controls.objetivoGeneral.controls; let i=index" id="tbl_objGeneral" class="divTableRow">
          <div class="divTableCell">{{ (i+1) }}</div>
          <div class="divTableCell">
            <input id="objetivoGeneral" formControlName="text" class="form-control" type="text" placeholder="Objetivo General">
          </div>
          <div class="divTableCell" id="dellCell">
            <button (click)="delObjGral(i)" type="button" class="btn btn-danger">Eliminar</button>
          </div>
       </div>
     </div>
  </div>
</div>

<强> Plunker Example

P.S。 id在文档中必须是唯一的。使用class代替id="tbl_objGeneral"