...">

Form controls undefined

My form is made as follows:

<form #form="ngForm" novalidate (ngSubmit)="register(form);">
    <div class="registerinput">
        <label for="firstname">First Name</label>
        <input #firstname="ngModel" type="text" name="firstname" maxlength="30" pattern="[a-zA-Z ]*" required ngModel>
        <div [hidden]="!form.controls.firstname.touched && !form.controls.firstname.errors?.required" class="alert-danger">
            Please enter your name
        </div>
        <div [hidden]="!form.controls.firstname.touched && !form.controls.firstname.errors?.maxlength" class="alert-danger">
             Max length is 30 characters
        </div>
        <div [hidden]="!form.controls.firstname.touched && !form.controls.firstname.errors?.pattern" class="alert-danger">
             Only letters are allowed
        </div>
    </div>
    <div class="registerinput">
        <button type="submit" class="btn-register">Register</button>
    </div>
</form>

I get the following error:

EXCEPTION: Uncaught (in promise): Error: Error in http://localhost:3000/app/register/register.component.html:7:17 caused by: Cannot read property 'touched' of undefined
Error: Error in http://localhost:3000/app/register/register.component.html:7:17 caused by: Cannot read property 'touched' of undefined

It seems he cannot find my controls. However, when I try to print form.controls, I get the following result:

enter image description here

So, in this case, he finds them in order. What is the problem? I did something similar in the past that worked.

UPDATE: I found out that instead of, for example form.controls.firstname.touched, I should access them using only firstname.touched. I just don’t understand why, because I have another file in the same project where I use forms that were made exactly the same, but in this I used form.controls.*. I think you can use firstname.touchedit if you specified a template reference variable, but I don’t know under what circumstances you can use it form.controls.*.

+4
1

:

<form #form="ngForm" novalidate (ngSubmit)="register(form);">
    <div class="registerinput">
        <label for="firstname">First Name</label>
        <input #firstname="ngModel" type="text" name="firstname" maxlength="30" pattern="[a-zA-Z ]*" required ngModel>
        <div [hidden]="!firstname.touched && !firstname.errors?.required" class="alert-danger">
            Please enter your name
        </div>
        <div [hidden]="!firstname.touched && !firstname.errors?.maxlength" class="alert-danger">
             Max length is 30 characters
        </div>
        <div [hidden]="!firstname.touched && !firstname.errors?.pattern" class="alert-danger">
             Only letters are allowed
        </div>
    </div>
    <div class="registerinput">
        <button type="submit" class="btn-register" [disabled]='!form.valid'>Register</button>
    </div>
</form>

.

+2

Source: https://habr.com/ru/post/1673617/


All Articles