Search code examples
classtemplatesangularrequired

Angular2 applies ng-valid class to field when required attribute is conditional and value is still empty


I'm using angular 2.3.1 and I have the following html element in a component template:

<input class="form-control" type="text" id="password" name="password" 
placeholder="Password" [attr.required]="requirePasswd ? true : null"
[(ngModel)]="password">

If this is a new user (id is empty) then I want to require the password. If not a new user, the password is optional.

The conditional attribute is working but when used conditionally, the ng-valid class is applied even though the field still has no value.

If I hard code the required attribute, angular2 appropriately sets the class to ng-invalid, but when I make it conditional and requirePass is true, this element always has the ng-valid class even when it's still invalid.


Solution

  • Check out the Angular 2 source. You'll see that required is actually a Directive, so you'll need to use that syntax to setup your binding here.

    It also takes a value, it doesn't just have to be present, so instead of passing in null you can just pass in true/false.

    [required]="requirePasswd"