Search code examples
angularvalidationclient-side-validation

Validating pre populated input field angular


I have the following code:

<h1>New Book</h1>
<form  #f="ngForm" (ngSubmit)="submit(f)">
   <div class="form-group">
        <label for="group">Group</label>
        <select id="group" class="form-control" (change)="onGroupChange()" [(ngModel)]="groupId" name="groupId">
            <option value=""></option>
            <option *ngFor="let g of groups" value="{{g.id}}">{{g.name}}</option>
        </select>
    </div>
    <div class="form-group">
        <label for="registrationNumber">Registration Number</label>
        <input required ngModel name="registrationNumber" #registrationNumber="ngModel" id="registrationNumber" class="form-control" value={{regId}}/>
        <div class="alert alert-danger" *ngIf="!registrationNumber && !registrationNumber.valid">Registration Number  is required.</div>
    </div>
 <button class="btn btn-primary" [disabled]="!f.valid">Save</button>
</form>

As you can see, the button is disabled if one of the form's values is invalid. The problem is that the registration number is populated when you choose a group in the group drop down list. Even after populating the registration number field, the save button is still disabled.What kind of validation should I write in the *ngIf of the registration Number to tell angular to mark the field as ok if the field has value.

In other words, what should go in the ngIf below?

<div class="alert alert-danger" *ngIf=" ? "**>Registration Number  is required.</div>
    </div>

Solution

  • You need to set the value using ngModel and then the validation should work as expected.

    <input required [ngModel]="regId" name="registrationNumber" #registrationNumber="ngModel" id="registrationNumber" class="form-control"/>
    

    Additionaly, you can simplify your ngIf by using the null-coalescing operator

    <div class="alert alert-danger" *ngIf="!registrationNumber?.valid">Registration Number  is required.</div>