动态控件到对象打字稿

时间:2017-02-15 14:05:25

标签: javascript angular typescript

我有一张表格,必须由一个主要人填写,他也可以填写他的配偶和孩子的表格。 (Picture of the form) 在儿童要求之前它一直很好。

我制作了这个模型:

export class RequestForm{

 model = {
    main: { apellido: "", nombre: "", documento: "", sexo: "", fechaNacimiento: "", localidad: "", calle: 0, piso: 0, depto: 0, edificio: 0, telefono: "", celular: "", mail: "" },
    spouse: { apellido: "", nombre: "", documento: "", sexo: "", fechaNacimiento: "", localidad: "", calle: 0, piso: 0, depto: 0, edificio: 0, telefono: "", celular: "", mail: "" },
    children: [{ apellido: "", nombre: "", documento: "", sexo: "", fechaNacimiento: "", localidad: "", calle: 0, piso: 0, depto: 0, edificio: 0, telefono: "", celular: "", mail: "" }]
};

然后,当单击“完成表单”按钮时,将调用此函数:

 finish() {
    this.model.main= {
        apellido: this.titularApellido.value, nombre: this.titularNombre.value, documento: this.titularDocumento.value
        , sexo: this.titularSexo.value, fechaNacimiento: this.titularFechaNacimiento.value, localidad: this.titularLocalidad.value
        , calle: this.titularCalle.value, piso: this.titularPiso.value, depto: this.titularDepto.value, edificio: this.titularEdificio.value
        , telefono: this.titularTelefono.value, celular: this.titularCelular.value, mail: this.titularMail.value
    };

    this.model.spouse = {
        apellido: this.conyugeApellido.value, nombre: this.conyugeNombre.value, documento: this.conyugeDocumento.value
        , sexo: this.conyugeSexo.value, fechaNacimiento: this.conyugeFechaNacimiento.value, localidad: this.titularLocalidad.value
        , calle: this.titularCalle.value, piso: this.titularPiso.value, depto: this.titularDepto.value, edificio: this.titularEdificio.value
        , telefono: this.conyugeTelefono.value, celular: this.conyugeCelular.value, mail: this.conyugeMail.value
    };       

    this.persistPerson(this.model.main);
    this.persistPerson(this.model.spouse);
}

我真的不知道如何动态制作子控件然后在finish函数中绑定。 有一个输入属性ngModel但是当我添加它时,控件会中断。

由于

PD。我这样做是为了重复控件,但是我无法为控件设置id,所以我丢失了引用。当我这样做时,孩子是一个数组,+和 - 按钮推动并从数组中删除对象

                        <ul style="list-style-type:decimal">
                            <li *ngFor="let child of children" style="display:list-item">

                                <table>
                                    <tr>
                                        <td>
                                            <md-input textoLabel="Apellido" type="text" [disabled]="esModoVisualizacion()"
                                                      placeholder="Apellido"
                                                      style="width:130px;"></md-input>
                                        </td>
                                        <td>
                                            <md-input ..
                                              .
                                              .
                                </table>
                            </li>
                        </ul>

1 个答案:

答案 0 :(得分:0)

正如评论中所提到的,我建议你使用动态表单,它可以让你有一个很好的对象来处理和提取值:

这是一个基于您的代码的简化示例,使用FormGroupFormControlFormArray。您还可以使用验证程序检查表单是否有效。

首先从FormGroup开始,在其中添加所有的formcontrol。首先导入必要的东西并在构造函数中注入FormBuilder:

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

constructor(private fb: FormBuilder) {  }

然后构建表单

patientForm: FormGroup;

ngOnInit() {
  this.patientForm = this.fb.group({
    firstname: ['', [Validators.required]], // add different validators
    lastname: ['']
    children: this.fb.array([ // create an FormArray for children
      this.initChildren()
    ])
  });
}

然后为孩子建立FormArray以及在表单中添加新孩子的方法:

initChildren() {
  return this.fb.group({ // create a new group for children
    firstname: ['']
  })
}

addChild() { // adds a new formcontrol to your children formarray
  const control = <FormArray>this.patientForm.controls['children'];
  control.push(this.initChildren())
}

然后在视图中创建您的实际表单:

<form [formGroup]="patientForm" (ngSubmit)="submit(patientForm.value)"> <!-- add formgroup -->
  <label>Patient firstname: </label>
  <input formControlName="firstname"/> <!-- all fields need corresponding formcontrol name -->
  <label>Patient lastname: </label>
  <input formControlName="lastname"/>

  <div formArrayName="children"> <!-- Your formarray and below iterate the array -->
    <div *ngFor="let child of patientForm.controls.children.controls; let i = index" >
      <div formGroupName="{{i}}"> <!-- All children need unique formControl, here we used index -->
        <label>Child {{i+1}} firstname: </label>
        <input formControlName="firstname" />
      </div>
    </div>
  </div>
</form>

通过这种方式,您可以获得一个很好的对象,可以摆脱所有[(ngModel)],这会让您的生活变得更轻松;)

在提交上面的代码后,你最终会得到一个像这样的对象:

{
  "firstname": "",
  "lastname": "",
  "children": [
    {
      "firstname": ""
    }
  ]
}

link可能会有所帮助,此链接基本上显示了我为您创建的示例,但进一步说明,我还使用上面的代码为您创建了Plunker! :)

希望这有帮助!

相关问题