简体   繁体   English

获取反应形式中的值

[英]get values in Reactive Forms

I'm having trouble populating my entity data on my reactive form. 我在反应式表单上填充实体数据时遇到问题。

I can get the data, but I do not know how or when is the best time to fill out my form with these values. 我可以获取数据,但是我不知道如何或何时将这些值填写表格的最佳时间。

this is my form: 这是我的表格:

import { Component, OnInit, Input } from '@angular/core';

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

import { Empresa } from '../empresa.model';

import { HttpClient } from '@angular/common/http';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-empresa-detalhe',
  templateUrl: './empresa-detalhe.component.html',
  styleUrls: ['./empresa-detalhe.component.scss']
})
export class EmpresaDetalheComponent implements OnInit {

  empresaForm: FormGroup;

  nomeControl: FormControl;
  statusControl: FormControl;

  empresa: Empresa = {};

  constructor(private route: ActivatedRoute, private http: HttpClient, private fb: FormBuilder) {}

  ngOnInit() {
    this.getEmpresa(this.route.snapshot.params['nome']);
    this.createForm();
  }

  createForm() {
    this.nomeControl = new FormControl('', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10)
    ]);
    this.statusControl = new FormControl('', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10)
    ]);

    this.empresaForm = this.fb.group({
      nome: this.nomeControl,
      status: this.statusControl
    });
  }

  onSubmit() {
    const empresa = this.empresaForm.value as Empresa;
    console.log('Empresa: ', empresa);
  }

  getEmpresa(nome) {
    this.http.get('http://localhost:8080/app-rest/api/empresasAereas/nome/' + nome).subscribe(data => {
      this.empresa = data;
      console.log(this.empresa); // this return my data with values
    });
  }

}

my getEmpresa return my empresa model, What is the best way to fill my form data with my entity data? 我的getEmpresa返回我的Empresa模型,用实体数据填充表单数据的最佳方法是什么?

You should update your form after the http get call returns. 您应该在http get调用返回后更新表单。 You can use patchValue or setValue methods. 您可以使用patchValuesetValue方法。

patchValue() patchValue()

Patches the value of the FormGroup. 修补FormGroup的值。 It accepts an object with control names as keys, and will do its best to match the values to the correct controls in the group. 它接受带有控件名称作为键的对象,并将尽最大努力将值与组中的正确控件匹配。

setValue() 设定值()

Sets the value of the FormGroup. 设置FormGroup的值。 It accepts an object that matches the structure of the group, with control names as keys. 它接受与组结构匹配的对象,控件名称为键。

This method performs strict checks, so it will throw an error if you try to set the value of a control that doesn't exist or if you exclude the value of a control. 此方法执行严格的检查,因此如果您尝试设置不存在的控件的值或排除控件的值,它将引发错误。

It accepts both super-sets and sub-sets of the group without throwing an error. 它接受组的超集和子集,而不会引发错误。

getEmpresa(nome) {
  this.http.get('http://localhost:8080/app-rest/api/empresasAereas/nome/' + nome).subscribe(data => {
    empresaForm.setValue(data)
  });
}

Also, your createForm() method can be simplified like this: 同样,您的createForm()方法可以像这样简化:

createForm() {
  this.empresaForm = this.fb.group({
    nomeControl: ['', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10)
    ]],
    statusControl: ['', [
      Validators.required,
      Validators.minLength(3),
      Validators.maxLength(10)
    ]],
  })
}

The first thing you should do in you ngOnInit() is to build the form and then call the getEmpresa() function. ngOnInit()应该做的第一件事是构建表单,然后调用getEmpresa()函数。 (you are doing the reverse). (您正在做相反的事情)。

ngOnInit() {
    this.createForm();
    this.getEmpresa(this.route.snapshot.params['nome']);
}

and then set the form data in your getEmpresea() function , Ideally this should be the place you set the data to the form, but anyway that will depend on how you want to do the implementation. 然后在getEmpresea() function设置表单数据,理想情况下,这应该是将数据设置为表单的位置,但是无论如何,这将取决于您要如何执行实现。

If the data returned by your getEmpresa() function has the same structure as that of the form, then you can simply do: 如果您的getEmpresa()函数返回的数据具有与表单相同的结构,则可以简单地执行以下操作:

this.http.get('http://localhost:8080/app-rest/api/empresasAereas/nome/' + nome).subscribe(data => {
  ...
  this.empresaForm.setValue(data);
  ...
});

If your form has a different structure, then do something like inside the subscription: 如果您的表单具有不同的结构,请在订阅中执行以下操作:

this.empresaForm.setValue({
   nome:    data.nomeValue,
   status: data.statusValue
});

Here for setting values to the form model you have options like: setValue() and patchValue() . 您可以在此处为表单模型设置值,例如: setValue()patchValue() @Tomasz Kula has clearly stated the difference, You can also See: this link from angular. @Tomasz Kula明确指出了区别,您还可以看到: 此链接来自角度。

if you console complete object of reactive form. 如果您管理反应形式的完整对象。 you find a key with name "value". 您会发现一个名为“值”的键。

console.log(this.empresaForm.value)

contain all FormControls values, 包含所有FormControls值,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM