First always empty input in Formgroup

Asked

Viewed 288 times

-1

The first input of the form does not load the value from the indexedDB, nor does it carry a new value typed for recording in the database.

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FormBuilder } from '@angular/forms';

import { ConnectionFactory } from 'src/app/core/connection/connection.service';
import { ClientesDAO } from 'src/app/core/dao/clientesDao';

@Component({
    templateUrl: 'cadastroClientes.component.html'
})
export class CadastroClientesComponent implements OnInit {

    clienteId;
    tituloPagina;
    clientesDAO;
    clienteForm;

    constructor(
        private activatedRoute: ActivatedRoute,
        private formBuilder: FormBuilder
    ) { }

    ngOnInit() {
        this.clienteId = parseInt(this.activatedRoute.snapshot.params.clienteId);

        this.tituloPagina = this.clienteId ? 'Alterar Cliente' : 'Novo Cliente';

        ConnectionFactory.getConnection()
            .then(connection => this.clientesDAO = new ClientesDAO(connection))
            .then(this.carregaCliente.bind(this))
            .then(this.carregaForm.bind(this));
    }

    carregaCliente() {
        if (this.clienteId)
            return this.clientesDAO.select(this.clienteId);

        return { nomeFantasia: '', cnpj: '', telefone: '' };
    }

    carregaForm(cliente) {
        this.clienteForm = this.formBuilder.group({
            nomeFantasia: [cliente.nomeFantasia],
            cnpj: [cliente.cnpj],
            telefone: [cliente.telefone]
        })
    }

    salvar() {
        const cliente = {
            id: (this.clienteId ? this.clienteId : this.clientesDAO.AUTO_INCREMENT),
            nomeFantasia: this.clienteForm.value.nomeFantasia,
            cnpj: this.clienteForm.value.cnpj,
            telefone: this.clienteForm.value.telefone
        };

        this.clientesDAO.save(cliente)
            .then(cliente => {
                !this.clienteId &&
                    this.clienteForm.reset();
                alert(`Cliente ${cliente.id} - ${cliente.nomeFantasia} salvo.`);
            });
    }

}

<h2 class="bd-title" [textContent]="tituloPagina"></h2>

<form [formGroup]="clienteForm" (ngSubmit)="salvar()">
    <div class="form-group">
        <input type="text" class="form-control" formControlName="nomeFantasia" aria-describedby="Nome Fantasia"
            placeholder="Nome Fantasia">
    </div>
    <div class="form-group">
        <input type="text" class="form-control" formControlName="cnpj" aria-describedby="CNPJ" placeholder="CNPJ">
    </div>
    <div class="form-group">
        <input type="text" class="form-control" formControlName="telefone" aria-describedby="Telefone" placeholder="Telefone">
    </div>
    <button type="submit" class="btn btn-primary float-right ml-1">Salvar</button>
    &nbsp;
    <button type="button" class="btn btn-secondary float-right" [routerLink]="['/clientes']">Voltar</button>
</form>

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { ReactiveFormsModule } from '@angular/forms';

import { CadastroClientesComponent } from './cadastro/cadastroClientes.component';
import { listaClientesComponent } from './lista/listaClientes.component';

@NgModule({
    declarations: [
        CadastroClientesComponent,
        listaClientesComponent
    ],
    imports: [
        CommonModule,
        RouterModule,
        ReactiveFormsModule
    ]
})
export class ClientesModule { }
  • Put the question code in itself instead of using links.

  • Try creating a stackblitz where your error occurs

  • tries to post the code of your entire component

  • Guy creates a minimum stackblitz of error, no one has time to enter your project download it, download the departments to reproduce the error.

  • 1

    Are there any errors in the console? Try adding an ngIf in the form <form *ngIf="formGroup" [formGroup]="clienteForm" (ngSubmit)="save()">

  • Worked with *ngIf="clienteForm"

Show 1 more comment

1 answer

1


The problem is that formGroup is undefined until its answer. Either you use ngIf or initialize the empty form in init.

<form *ngIf="formGroup" [formGroup]="clienteForm" (ngSubmit)="salvar()"> 
  • It makes perfect sense, but I always thought the Angular update mechanism would do it for me, rebuild the form when I assigned the formBuilder.

  • The big "problem" is that I want to reuse the form for both registration and editing. Looking at my code, however simple it is, maybe even a clean code? You would change something thinking about design, this ugly?

  • in the load methodForm(client) it was better client to be opciconal ai if vc n pass anything it incites with an empty client

  • Okay, I understand, but give client.namFantasia will be Undefined, and cause error when creating the form with formBuilder.group. Understand? I don’t want to have to create the form in init and then repeat the code in Form.

  • would be an empty string right? client type={filename: '', ...

  • I don’t understand exactly how you propose to do that. You mean to load Only return the select in the edition (edition = if clienteId), otherwise nothing returns. And client becomes Undefined in the datasheet. You can show me a code snippet?

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.