Angular 4 - 使用JSON数据填充表单不起作用

时间:2018-05-22 16:24:55

标签: json angular forms typescript

我必须从客户端编辑数据。我有一个表单,在其中我单击一个按钮并重定向到一个表单,我希望它显示我刚刚点击的客户端的数据。 事实上,当我尝试将每个键与其值相关联时,表单构建器不起作用。

但是,如果我自己写下这个名字,比如硬编码,那么表单构建器的工作就像一个魅力!。

编辑component.ts

import { FuncionForm } from './../../interfaces/funcion_form';
import { FuncionService } from './../../services/funcion.service';
import { Combobox } from './../../interfaces/combobox';
import { ComboboxService } from './../../services/combobox.service';
import { Formulario } from './../../interfaces/formulario';
import { HttpClient } from '@angular/common/http';
import { SharedService } from './../../services/shared-service.service';
import { Component, OnInit } from '@angular/core';
import { Funcion } from '../../interfaces/funcion';
import {
  FormGroup,
  Validators,
  FormBuilder,
  FormControl,
  FormsModule,
  ReactiveFormsModule
} from '@angular/forms';

@Component({
selector: 'app-editar-funcion',
templateUrl: './editar-funcion.component.html',
styleUrls: ['./editar-funcion.component.css']
})
export class EditarFuncionComponent implements OnInit {

funcionCD:                number;
dadosFormulario :         FuncionForm;
funcionFormGroup:         FormGroup;
comboboxProfisArray :     Combobox;
comboboxAgrupProfArray :  Combobox;
comboboxAgrupCategArray : Combobox;
comboboxNacionArray :     Combobox;
myForm :                  FormGroup;  

 constructor(private sharedService : SharedService,
          private funcionService : FuncionService,
          private funcionFormBuilder: FormBuilder,
          private comboboxService: ComboboxService) 
 {}

ngOnInit() { 

this.sharedService.currentClientCD.subscribe(message => this.funcionCD = message); // Service to get the client ID

this.funcionService.GetDadosCliente(this.funcionCD).subscribe(
  (res:FuncionForm) => {
    this.dadosFormulario = res; // Interface to define a client


// This works!
this.myForm = new FormGroup({ 
  nome :          new FormControl("A name"),
  dt_nasc :       new FormControl("1998-02-25"),
  sexo :          new FormControl("0"),
  cd_nacion :     new FormControl("PT"),
  cd_agrup_prof : new FormControl("M"),
  cd_profis :     new FormControl("M"),
  cd_categ :      new FormControl("M"),
  loc_trab :      new FormControl("A company") 
  // This works!

  /* This doesn't!
 this.myForm = new FormGroup({ 
  nome :          new FormControl(this.dadosFormulario[0].nome),
  dt_nasc :       new FormControl(this.dadosFormulario[0].dt_nasc),
  sexo :          new FormControl(this.dadosFormulario[0].sexo),
  cd_nacion :     new FormControl(this.dadosFormulario[0].cd_nacion),
  cd_agrup_prof : new FormControl(this.dadosFormulario[0].cd_agrup_prof),
  cd_profis :     new FormControl(this.dadosFormulario[0].cd_profis),
  cd_categ :      new FormControl(this.dadosFormulario[0].cd_categ),
  loc_trab :      new FormControl(this.dadosFormulario[0].loc_trab) 
   */

 })      
}

编辑component.html

<div class="container">
 <h1>Editar dados do funcionário</h1>
 <hr>
 <div class="card">
 <div class="container">
  <div class="row">
    <div class="col-md-3" id="col-img">
        <img src="/img/1">
    </div>
    <div class="col-md-9" id="col-dados">
      <form class="form-horizontal" role="form" [formGroup]="myForm">

      <!-- 
        <div class="form-group row">
          <label class="col-md-12 col-form-label">Local de trabalho</label>
            <div class="col-md-12">
              <input formControlName="loc_trab" type="text" class="form-control">
            </div>
        </div>
      -->
        <div class="form-group row">
        <label class="col-md-12 col-form-label">Nome</label>
          <div class="col-md-12">
            <input formControlName="nome" type="text" class="form-control">
          </div>
        </div>

        <div class="form-group row">
        <label class="col-md-12 col-form-label">Data de nascimento</label>
          <div class="col-md-12">
            <input formControlName="dt_nasc" type="date" class="form-control">
          </div>
        </div>

        <div class="form-group row">
          <label class="col-md-12 col-form-label">Género</label>
          <div class="col-md-12">
            <select formControlName="sexo" type="text" class="form-control">
              <option value="0">Masculino</option>
              <option value="1">Feminino</option>
            </select>
          </div>
        </div>

        <div class="form-group row">
          <label class="col-md-12 col-form-label">Nacionalidade</label>
          <div class="col-md-12">
            <select formControlName="cd_nacion" type="text" class="form-control">
              <option *ngFor="let row of comboboxNacionArray" value="{{ row.cd }}">{{ row.nome }}</option>
            </select>
          </div>
        </div>

        <div class="form-group row">
          <label class="col-md-12 col-form-label">Agrupamento Profissional</label>
          <div class="col-md-12">
            <select formControlName="cd_agrup_prof" type="text" class="form-control">
              <option *ngFor="let row of comboboxAgrupProfArray" value="{{ row.cd }}">{{ row.nome }}</option>
            </select>
          </div>
        </div>

        <div class="form-group row">
          <label class="col-md-12 col-form-label">Profissão</label>
          <div class="col-md-12">
            <select formControlName="cd_profis" type="text" class="form-control">
              <option *ngFor="let row of comboboxProfisArray" value="{{ row.cd }}">{{ row.nome }}</option>
            </select>
          </div>  
        </div>

        <div class="form-group row">
          <label class="col-md-12 col-form-label">Categoria Profissional</label>
          <div class="col-md-12">
            <select formControlName="cd_categ" type="text" class="form-control">
              <option *ngFor="let row of comboboxAgrupCategArray" value="{{ row.cd }}">{{ row.nome }}</option>
            </select>
          </div>
        </div>

        <div class="form-group row">
          <label class="col-md-12 col-form-label">Local de trabalho</label>
          <div class="col-md-12">
            <input formControlName="loc_trab" type="text" class="form-control">
          </div>
        </div>

        <div class="form-group row">
          <div class="col-md-12" style="padding-top: 15px;">
              <button style="border-radius: 50px; float:right;" type="submit" class="btn btn-primary">Submeter</button>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>

一些screnshots

Working

Not working

我到处搜索,无法找到解决方案。 所有帮助都是折旧的!

PS:JSON数据是这样的。这就是&#34; 0&#34;在 this.dadosFormulario [0]

[
  {
    "nome": "MY NAME",
    "dt_nasc": "1978-05-26T00:00:00",
    "sexo": "0",
    "cd_nacion": "2", 
    "cd_agrup_prof": null,
    "cd_profis": "1",
    "cd_categ": "TS",
    "loc_trab": ""
   }
 ] 

2 个答案:

答案 0 :(得分:2)

你的this.dadosFormulario在onNgOnit()上将为null,这就是你没有在表单中看到任何值的原因..

funcionService

获取数据后,您需要使用patchValue更新表单

答案 1 :(得分:1)

要预先填充数据,FormGroup实例有两种方法。 setValue()&amp; patchValue()。收到服务器的响应后,只需使用以下方法setValue()patchValue()之一设置/修补值,两者都会设置form control FormGroup中的值。 setValue()设置FormGroup的每个表单控件的值。您不能在setValue()中省略任何表单控件,但如果您只想分配FormGroup的几个表单控件,那么您可以使用patchValue().

修改后的代码

ngOnInit() { 
    this.initializeForm();
    this.sharedService.currentClientCD.subscribe(message => this.funcionCD = message); // Service to get the client ID

    this.funcionService.GetDadosCliente(this.funcionCD).subscribe(
      (res:FuncionForm) => {
        this.dadosFormulario = res; // Interface to define a client

    this.myForm.setValue(
     {

        nome :      this.dadosFormulario[0].nome,
        dt_nasc :      this.dadosFormulario[0].dt_nasc,
        sexo :         this.dadosFormulario[0].sexo,
        cd_nacion :     this.dadosFormulario[0].cd_nacion,
        cd_agrup_prof : this.dadosFormulario[0].cd_agrup_prof,
        cd_profis :     this.dadosFormulario[0].cd_profis,
        cd_categ :      this.dadosFormulario[0].cd_categ,
        loc_trab :      this.dadosFormulario[0].loc_trab
    })

    });


initializeForm()
        {
            this.myForm = new FormGroup({ 
                nome :          new FormControl(),
                dt_nasc :       new FormControl(),
                sexo :          new FormControl(),
                cd_nacion :     new FormControl(),
                cd_agrup_prof : new FormControl(),
                cd_profis :     new FormControl(),
                cd_categ :      new FormControl(),
                loc_trab :      new FormControl() 
        }