首页 > 解决方案 > Angular 4 - 使用 JSON 数据填充表单不起作用

问题描述

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

但是,如果我自己写下名称,比如硬编码,表单生成器就像一个魅力!

编辑组件.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>

一些截图

在职的

不工作

我到处搜索,找不到解决方案。感谢所有帮助!

PS:JSON数据是这样的。这就是为什么this.dadosFormulario[0]中的“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": ""
   }
 ] 

标签: jsonangularformstypescript

解决方案


要预填充数据,FormGroup 实例有两种方法。setValue()& patchValue(). 在您收到来自服务器的响应后,只需使用这些方法之一设置/修补值,setValue()并且patchValue()都将值设置form controlFormGroup. 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() 
        }

推荐阅读