The full message I get when loading the component (at component initialization) is:
ERROR TypeError: Cannot 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 trace the execution, the applyCssErro(field) function is executed after the form is created.
I just don't understand where I'm going wrong. All the best.
You have a form that nests two other forms. When you create forms made up of other forms, the fields are not simply added to the parent form, you need to traverse the tree to get to them:
with what your HTML would be: