Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular input required field not working

I have a form used for creating a new entity as below:

<form #createAppForm="ngForm"
        (ngSubmit)="createApplication(createAppForm.value)"
        autocomplete="false" novalidate>
    <div class="form-group"
         [ngClass]="{'error': createAppForm.controls.applicationName?.invalid && createAppForm.controls.applicationName?.touched}">
    <label for="applicationName">Application Name</label>
    <em *ngIf="createAppForm.controls.applicationName?.invalid && createAppForm.controls.applicationName?.touched">Required</em>
    <input name="applicationName" required id="applicationName" type="text"
           class="form-control" placeholder="Name of application..." />
    </div>

I did not use ngModel in the input as the form is supposed to be blank when it comes up, and i'm submitting the createAppForm.value to the ngSubmit. However, whenever i check the form's valid property:

{{createAppForm.invalid}}

that is always returning false, even if i click in the input field and click out, without filling anything in. as a required field should it not return true?

I had used a similar form, editing data, in there i used [ngModel] and that works fine, validates the required field. Is [ngModel] needed here as well, and if so why? as i'm passing the form's values in.

like image 861
Paritosh Avatar asked Mar 06 '23 20:03

Paritosh


1 Answers

You need to add ngModel to your input to be able to make use of Angular's form validation.

In a nutshell, ngForm only checks for elements that have an ngModel and a name. Without these, Angular won't validate.

Change it to this:

<input name="applicationName" ngModel required id="applicationName" type="text" class="form-control" placeholder="Name of application..." />

More info on the official docs.

like image 73
Uğur Dinç Avatar answered Mar 11 '23 16:03

Uğur Dinç