Angular Rectangular Form 5: ERROR TypeError: Can not read property 'valid'

1

The complete message that I get when loading the component (in the initialization of it) is:

ERROR TypeError: Can not read property 'valid' of null at ProbaComponent.verifiesValidTouched

In the component I define the form like this:

formulario: FormGroup;
  	
.....
  	
this.formulario = this.formBuilder.group({
 	  averia : this.formBuilder.group({
		CODIGO: ['0],
		DESCRIP: ['', Validators.required],
		ESTADO: [0, Validators.required],
		TIPO: [0, Validators.required],
   	  }),
   	  informador : this.formBuilder.group({
		INF_NOME: ['', Validators.required],
		INF_TLNO: ['', Validators.required],
		INF_EMAIL: ['']
   	  }),
});

the html:

<div class="form-group">
<label for="INF_NOME" class="form-control-label">
      Teléfono para contacto</label>
<input type="text" class="form-control form-control-sm"
	 [ngClass]="aplicaCssErro('INF_NOME')"
	 id="INF_NOME"  formControlName="INF_NOME" autofocus>
</div>

And the function that the html calls:

verificaValidTouched(campo) {
 return !this.formulario.get(campo).valid && this.formulario.get(campo).touched;
}
  
aplicaCssErro(campo) {
   if (this.formulario && this.verificaValidTouched(campo)) {
     return 'is-invalid';
   } else {
     return '';
   }
}

If I make a trace of the execution, the function applyCssErro (field) is executed after the form is created.

I do not quite understand where I'm erecting myself. Greetings.

    
asked by Apicito Diaz 19.12.2017 в 13:21
source

1 answer

1

You have a form that nests two other forms. When you create forms composed of other forms, the fields are not simply added to the parent form, you need to go through the tree to get to them:

verificaValidTouched(form, campo) {
 return !this.formulario.get(form).get(campo).valid && this.formulario.get(form).get(campo).touched;
}

aplicaCssErro(form, campo) {
   if (this.formulario && this.formulario.get(form) && this.verificaValidTouched(form,campo)) {
     return 'is-invalid';
   } else {
     return '';
   }
}

with what your HTML would be:

<input type="text" class="form-control form-control-sm"
 [ngClass]="aplicaCssErro('informador','INF_NOME')"
 id="INF_NOME"  formControlName="INF_NOME" autofocus>
    
answered by 19.12.2017 / 13:42
source