反应形式不接收默认输入值 [英] reactive form not receive default input value

查看:55
本文介绍了反应形式不接收默认输入值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是棱角形,我有一个反应式表格可以编辑项目.当我打开要编辑的组件时,输入会正确加载对象的值,但是如果我不单击输入并更改值,则反应形式的值将为空.

I'm using angular and I have a reactive form for editing an item. When I open the component for editing, the inputs load value for object correctly, but if I don't click the input and change value, the value in reactive form is empty.

我的代码在这里:

 <form [formGroup]="entidadesForm">
        <div class="row">
            <div class="col-lg-12">
                <nb-card>
                    <nb-card-header>Digite os dados solicitados</nb-card-header>
                    <nb-card-body>
                        <div class="form-group">
                            <label class="container-title" >Nome</label>
                            <input type="text" autocomplete="off" formControlName="Nome"   value="{{nome}}" class="form-control" placeholder="Nome" class="form-control"
                            />
                        </div>
                        <div class="form-group" *ngIf="entidade === 'setor' || entidade === 'unidadeproduto' " >
                            <label class="container-title">Descricao</label>
                            <input type="text" autocomplete="off" value="{{descricao}}"placeholder="Descricao" class="form-control"  formControlName="Descricao"
                            />
                        </div>
                        <div class="form-group" *ngIf="entidade === 'unidadeproduto' " >
                                <label class="container-title">Pode Fracionar</label>
                                <select class="form-control"  formControlName="PodeFracionar" >
                                    <option *ngIf="!atualizar"></option>
                                    <option [selected]="podeFracionar == 'S'" value="S" >Sim</option>
                                    <option [selected]="podeFracionar == 'N'" value="N" >Nao</option>
                                </select>
                            </div>

                    </nb-card-body>
                </nb-card>
            </div>

        </div>
    </form>

和ts文件

constructor(private fb: FormBuilder, private entidadesProdutoService: EntidadesProdutoService, private route : ActivatedRoute, private router: Router, private location: Location) {
    this.atualizar = false;
   }

  ngOnInit() {

    this.route.queryParams.subscribe( params =>{
       this.id = params['id'];
       this.nome = params['nome'];
       this.descricao = params['descricao'];
       this.podeFracionar = params['podeFracionar'];
       this.entidade = params['entidade'];
       if(this.id !== undefined) this.atualizar = true;
      });

    this.entidadesForm = new FormsModels(this.fb).formularioModel(this.entidade)

  }

  salvar( ){
    if(this.atualizar){
      this.entidadesProdutoService.atualizar(this.id, this.entidadesForm.value, this.entidade).subscribe(response => {
        this.location.back()
      },
    erro => console.log(erro))
    }else{
      this.entidadesProdutoService.salvar(this.entidadesForm.value, this.entidade).subscribe(response=>{
        this.location.back()
       },
     erro => {
       console.log(erro)
     })
    }
  }

在此处定义表单的组件:

the component to define a form here:

import { FormBuilder, FormGroup } from '@angular/forms';
export class FormsModels{

    constructor(public fb: FormBuilder){}

     public formularioModel(entidade): FormGroup{
        if(entidade === 'categoria' || entidade === 'marca' || entidade === 'subcategoria' || entidade === 'secao' ){
            return this.fb.group({
                Nome: this.fb.control('', [])
              })
            }

              else if(entidade === 'setor'){
            return this.fb.group({
                Nome: this.fb.control('', []),
                Descricao: this.fb.control('', [])
              })
            }
              else if(entidade === 'unidadeproduto'){
            return this.fb.group({
                Nome: this.fb.control('', []),
                Descricao: this.fb.control('', []),
                PodeFracionar: this.fb.control('', [])
              })
            }
        }

    }

当我加载组件时,输入加载正确的值,请参见图片:

when i load the component the inputs load correct value, see the image:

如果我仅编辑输入nome作为示例,则输入descricao的表单值和select输入pod fracionar的值将为空,请在此处查看控制台.

if i edit only input nome for exemple, the form value of inputs descricao and the select input pode fracionar will empty, see the console here.

推荐答案

您的输入字段显示了正确的值,因为您在html中设置了value="{{nome}}".

Your input fields are showing the correct value, because you set value="{{nome}}" in your html.

在创建FormGroup的过程中,您在控件配置this.fb.control('YOUR_EMTPY_STRING', [])中将一个空字符串设置为值,因此控件的值为空.

During your FormGroup creation you set an empty string as value in the control configuration this.fb.control('YOUR_EMTPY_STRING', []), so the value of the control is empty.

因此,您需要在创建FormGroup的过程中设置控件的值,例如像这样:

So you need to set the value of your controls during the FormGroup creation, e.g. like this:

this.route.queryParams.subscribe( params =>{
   this.id = params['id'];
   this.nome = params['nome'];
   this.descricao = params['descricao'];
   this.podeFracionar = params['podeFracionar'];
   this.entidade = params['entidade'];
   if(this.id !== undefined) this.atualizar = true;

   // After receiving the router params init your FormGroup
   this.entidadesForm = new FormsModels(this.fb).formularioModel(this.entidade)
});

...

public formularioModel(entidade): FormGroup{
    if(entidade === 'categoria' || entidade === 'marca' || entidade === 'subcategoria' || entidade === 'secao' ){
        return this.fb.group({
            Nome: this.fb.control(this.nome, [])
        })
    } else if(entidade === 'setor'){
        return this.fb.group({
            Nome: this.fb.control(this.nome, []),
            Descricao: this.fb.control(this.descricao, [])
        })
    } else if(entidade === 'unidadeproduto'){
        return this.fb.group({
            Nome: this.fb.control(this.nome, []),
            Descricao: this.fb.control(this.descricao, []),
            PodeFracionar: this.fb.control(this.podeFracionar, [])
        })
    }
}

否则,您可以像下面这样更新FormGroup的值:

Or otherwise you just update the value of your FormGroup like following:

this.route.queryParams.subscribe( params =>{
   this.id = params['id'];
   this.nome = params['nome'];
   this.descricao = params['descricao'];
   this.podeFracionar = params['podeFracionar'];
   this.entidade = params['entidade'];
   if(this.id !== undefined) this.atualizar = true;

   // Updates the value of your FromGroup
   this.entidadesForm.setValue({Nome: this.nome, Descricao: this.descricao, PodeFracionar: this.podeFracionar});
});

这篇关于反应形式不接收默认输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆