2

La aplicación que estoy haciendo me falla aquí, les agradecería que me ayudasen ya que llevo dos semanas atascado, espero disculpen si son errores evidentes ya que tengo poca experiencia con esto

gusuarios.component.html pagina

  <form method="POST"  [formGroup]="form" (ngSubmit)="enviar();" >
                    <div formGroupName="nombre">
                        <label for="nombre">Nombre</label>
                        <input 
                            formControlName="nombre"
                            placeholder="Nombre:" 
                            type="text" 
                            values="usuario.nombre" 
                            name="nombre"/>
                    </div>
                    <div formGroupName="id">
                        <input 
                            type="hidden" 
                            formControlName="id" 
                            values="usuario.id" 
                            name="id" 
                            value=0 />
                    </div>
                    <div formGroupName="apellidos">
                        <label for="apellidos">Apellidos</label>
                        <input 
                            placeholder="Apellidos:" 
                            type="text" 
                            values="usuario.apellidos" 
                            name="apellidos"
                            formControlName="apellidos"
                            />
                    </div>
                    <div formGroupName="email">
                        <label for="email">Email(Login)</label>
                        <input 
                            placeholder="Email:" 
                            type="text" 
                            values="usuario.email" 
                            name="email"
                            formControlName="email"
                            />
                    </div>
                    <div formGroupName="administrador">
                        <label for="administrador">Administrador</label>
                        <input 
                            type="checkbox" 
                            id="administrador" 
                            name="administrador" 
                            values="usuario.administrador"
                            formControlName="administrador"
                            />
                    </div>
                    <hr />
                    <a class="btn btn-default btn-block" (click)="enviar()">Enviar!</a>
                    <a class="btn btn-default btn-block" (click)="volver()">Cancelar</a>
                </form>

gusuarios.component.ts Controlador

import { UsuariosService } from '../../services/usuarios.service';
import { Router } from '@angular/router';
import { Usuario } from '../../interfaces/usuario';
import {Component, ElementRef, ViewChild, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
@Component({
  selector: 'app-gusuarios',
  templateUrl: './gusuarios.component.html',
  styleUrls: ['./gusuarios.component.css']
  })

export class GUsuariosComponent implements OnInit {  
  title = 'Gestión de usuarios';
  form: FormGroup;
  static readonly clase:string = 'GUsuariosComponent';
  submitted = false;
  usuarios:any = [];
  usuario:Usuario = new Usuario();
  error:string = '';

  constructor(private usuariosService:UsuariosService, private router:Router,private fb: FormBuilder){
    console.log(GUsuariosComponent.clase+".constructor. entra");
    usuariosService.getUsuarios(this);
    console.log(GUsuariosComponent.clase+".constructor. sale");
  };
  ngOnInit() {
    console.log(GUsuariosComponent.clase+".ngOnInit. entra");
    this.form= this.fb.group({
      nombre: ['', Validators.required],
      id:[0],
      apellidos: [''],
      email: ['', [Validators.required, Validators.email]],
      administrador: [0, Validators.required]
    });
    console.log(GUsuariosComponent.clase+".ngOnInit. sale");
  }
  modificar(index:number){
    this.usuario=this.usuarios[index];
  }
  eliminar(index:number){
    this.usuariosService.eliminarUsuario(this, this.usuarios[index].id, index);
  }
  enviar(){
    this.submitted = true;

    // stop here if form is invalid
    if (this.form.invalid) {
        return;
    }
    this.usuariosService.guardarUsuario(this, document);
  }
  volver(){
    this.router.navigate(['admin']);
  } 
    // convenience getter for easy access to form fields
  get f() { return this.form.controls; }

} 

Me muestra diferentes errores, ¿Me pueden ayudar?

Errores ................................................................................. Error1 .................................................................................




     **ERROR Error: Cannot find control with path: 'nombre -> nombre'
        at _throwError (forms.js:2144)
        at setUpControl (forms.js:2052)
        at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:5281)
        at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:5882)
        at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:5803)
        at checkAndUpdateDirectiveInline (core.js:22095)
        at checkAndUpdateNodeInline (core.js:23363)
        at checkAndUpdateNode (core.js:23325)
        at debugCheckAndUpdateNode (core.js:23959)
        at debugCheckDirectivesFn (core.js:23919)**

................................................................................. Error2 .................................................................................


       GUsuariosComponent.html:29 ERROR Error: Cannot find control with path: 'id -> id'
        at _throwError (forms.js:2144)
        at setUpControl (forms.js:2052)
        at FormGroupDirective.push../node_modules/@angular/forms/fesm5/forms.js.FormGroupDirective.addControl (forms.js:5281)
        at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName._setUpControl (forms.js:5882)
        at FormControlName.push../node_modules/@angular/forms/fesm5/forms.js.FormControlName.ngOnChanges (forms.js:5803)
        at checkAndUpdateDirectiveInline (core.js:22095)
        at checkAndUpdateNodeInline (core.js:23363)
        at checkAndUpdateNode (core.js:23325)
        at debugCheckAndUpdateNode (core.js:23959)
        at debugCheckDirectivesFn (core.js:23919)

.................................................................................

4
  • Bueno, el problema que veo y que te marca en GUsuariosComponent.html:6 es que tienes los [formControlName]="nombre", [formGroupName]="form", debes quitarle las llaves, quedaría así: formControlName="nombre", formGroupName="form". Prueba con ello.
    – CamiloJc
    el 30 abr. 2019 a las 15:43
  • las he quitado y sale el mismo error el 30 abr. 2019 a las 17:09
  • Lo he cambiado... el 2 may. 2019 a las 13:25
  • Lo edite......................... el 3 may. 2019 a las 7:28

2 respuestas 2

2

El problema esta en el archivo gusuarios.component.html, no tienes que poner la directiva formGroupName en las etiquetas input, porque ya tienes la directiva formGroup en form. Si quisieras poner un subgrupo en un formulario si que puedes utilizar la directiva formGroupName, pero no dentro de un input. Aquí hay mas información sobre FormGroupName.

Quedaría así el archivo HTML:

<form method="POST" [formGroup]="form" (ngSubmit)="enviar();" >
  <label for="nombre">Nombre</label>
  <input 
      formControlName="nombre" 
      placeholder="Nombre:" 
      type="text" 
      values="usuario.nombre" 
      name="nombre"/>
  <input 
      type="hidden" 
      formControlName="id" 
      values="usuario.id" 
      name="id" 
      value=0 />
  <label for="apellidos">Apellidos</label>
  <input 
      placeholder="Apellidos:" 
      type="text" 
      values="usuario.apellidos" 
      name="apellidos"
      formControlName="apellidos"/>
  <label for="email">Email(Login)</label>
  <input 
      placeholder="Email:" 
      type="text" 
      values="usuario.email" 
      name="email"
      formControlName="email"/>
  <label for="administrador">Administrador</label>
  <input 
      type="checkbox" 
      id="administrador" 
      name="administrador" 
      values="usuario.administrador"
      formControlName="administrador"/>
  <hr />
  <a class="btn btn-default btn-block" (click)="enviar()">Enviar!</a>
  <a class="btn btn-default btn-block" (click)="volver()">Cancelar</a>
</form>
0

He hecho cambios pero no me funciona bien la validacion

gusuarios.component.ts

import { UsuariosService } from '../../services/usuarios.service';
import { Router } from '@angular/router';
import { Usuario } from '../../interfaces/usuario';
import {Component, ElementRef, ViewChild, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators, FormControl} from "@angular/forms";
@Component({
  selector: 'app-gusuarios',
  templateUrl: './gusuarios.component.html',
  styleUrls: ['./gusuarios.component.css']
  })

export class GUsuariosComponent implements OnInit {  
  title = 'Gestión de usuarios';
  form: FormGroup;
  static readonly clase:string = 'GUsuariosComponent';
  submitted = false;
  usuarios:any = [];
  usuario:Usuario = new Usuario();
  error:string = '';

  constructor(private usuariosService:UsuariosService, private router:Router,private fb: FormBuilder){
    console.log(GUsuariosComponent.clase+".constructor. entra");
    usuariosService.getUsuarios(this);
    console.log(GUsuariosComponent.clase+".constructor. sale");
  };
  ngOnInit() {
    console.log(GUsuariosComponent.clase+".ngOnInit. entra");
    this.form= this.fb.group({
      nombre :new FormGroup({
        'nombre': new FormControl('',Validators.required)
      }) ,
      id: new FormGroup({
        'id':new FormControl(0)
      }),
      apellidos: new FormGroup({ 
        'apellidos': new FormControl('')
      }),
      email: new FormGroup({
        'email': new FormControl('',Validators.compose([Validators.required, Validators.email]))
      }),
      password: new FormGroup({
        'password': new FormControl('', Validators.compose([Validators.required, Validators.minLength(8)]))
      }),
      administrador: new FormGroup({
         'administrador': new FormControl(0, Validators.required)
      })
    });
    console.log(GUsuariosComponent.clase+".ngOnInit. sale");
  }
  modificar(index:number){
    this.usuario=this.usuarios[index];
  }
  eliminar(index:number){
    this.usuariosService.eliminarUsuario(this, this.usuarios[index].id, index);
  }
  enviar(){

    this.submitted = true;

    // stop here if form is invalid
    if (this.form.invalid) {
        return;
    }
    this.usuariosService.guardarUsuario(this, document);
  }
  volver(){
    //console.log(nombre.errors);
    //this.router.navigate(['admin']);
  } 
    // convenience getter for easy access to form fields
  get f() { return this.form.controls; }

} 

gusuario.component.html

        <form method="POST"  [formGroup]="form" (ngSubmit)="enviar();" >
            <table width="100%" >
            <tr>
                <td>
                    <label for="nombre">Nombre</label>
                </td><td>
                    <div formGroupName="nombre">
                        <input 
                            class="form-control"
                            formControlName="nombre"
                            placeholder="Nombre:" 
                            type="text" 
                            value="usuario.nombre" 
                            name="nombre"/>
                    </div>
                    <div formGroupName="id">
                        <input 
                            type="hidden" 
                            formControlName="id" 
                            values="usuario.id" 
                            name="id" 
                            value=0 />
                    </div>
                    <label
                      [ngClass]="form.controls['nombre'].hasError('required')   ? 'text-danger' : 'text-success'"
                    >
                      <i class="material-icons">
                        {{ form.controls['nombre'].hasError('required')  ? 'cancel' :
                        'check_circle' }}
                      </i>
                      ¡El nombre es obligatorio!
                    </label>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="apellidos">Apellidos</label>
                </td><td>
                    <div formGroupName="apellidos">
                        <input 
                            class="form-control"
                            placeholder="Apellidos:" 
                            type="text" 
                            value="usuario.apellidos" 
                            name="apellidos"
                            formControlName="apellidos"
                            />
                    </div>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="email">Email(Login)</label>
                </td><td>
                    <div formGroupName="email">
                        <input
                            class="form-control"
                            placeholder="Email:" 
                            type="text" 
                            value="usuario.email" 
                            name="email"
                            formControlName="email"
                            />
                    </div>
                    <label
                      [ngClass]="form.controls['email'].hasError('required') || form.controls['email'].hasError('email')  ? 'text-danger' : 'text-success'"
                    >
                      <i class="material-icons">
                        {{ form.controls['email'].hasError('required') ||
                        form.controls['email'].hasError('email') ? 'cancel' :
                        'check_circle' }}
                      </i>
                      ¡El email es incorrecto!
                    </label>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="email">password</label>
                </td>
                <td>
                    <div formGroupName="password">
                        <input 
                            class="form-control"
                            placeholder="password:" 
                            type="password" 
                            value="usuario.password" 
                            name="password"
                            formControlName="password"
                            />
                    </div>
                    <label
                      [ngClass]="form.controls['password'].hasError('required') || form.controls['password'].hasError('minLength')  ? 'text-danger' : 'text-success'"
                    >
                      <i class="material-icons">
                        {{ form.controls['password'].hasError('required') ||
                        form.controls['password'].hasError('minLength') ? 'cancel' :
                        'check_circle' }}
                      </i>
                      ¡El password es incorrecto!
                    </label>
                </td>
            </tr>
            <tr>
                <td>
                    <label for="administrador">Administrador</label>
                </td><td>
                    <div formGroupName="administrador">
                        <input 
                            class="form-control"
                            type="checkbox" 
                            id="administrador" 
                            name="administrador" 
                            value="usuario.administrador"
                            formControlName="administrador"
                            />
                    </div>

                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <button class="btn btn-default btn-block" (click)="enviar()" [disabled]="!form.valid">Enviar!</button>
                    <button class="btn btn-default btn-block" (click)="volver()">Cancelar</button>
                </td>
            </tr>
            </table>
        </form>

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.