what is the proper way to dynamically mark a field as required using Angular 2 Forms?

lhan picture lhan · Oct 17, 2016 · Viewed 11.1k times · Source

Using Angular 2 (2.0.0), what is the recommended way to dynamically mark a field as required, using Angular Forms?

In all of their examples, the required attribute is just added like:

<input type="text" class="form-control" id="name" required>

What if the model I'm binding to has an IsRequired property, that will be true/false?

If I use something like:

<input [(ngModel)]="field.Value" type="text" value="{{field.Value}}" [attr.required]="field.IsRequired"/>

That renders on the page like (note the ="true"):

<input type="text" required="true" />

For some reason, Angular doesn't appear to recognize this attribute when it has an actual value (the ="true") so when this field is blank, my form itself still is valid:

<form class="ng-untouched ng-pristine ng-valid">

So it would appear that I must use required and not required="true", but how can I add that attribute in dynamically?

What also doesn't work:

<input type="text" {{ getRequiredAttr(field) }} />

Thought I might be able to have a function that returns my string "required" based on the field, that just gives templating errors.

Is there a way to accomplish this and render only required for my attribute? Or a way to make Angular recognize this attribute when it has a value of true/false?

FWIW - I've verified that I can use *ngIf to write two near-identical <input type='text' /> controls based on my IsRequired property and hardcode one with the required attribute but that seems pretty hacky. Hoping there's a better way!

Answer

Edison D&#39;souza picture Edison D'souza · Sep 8, 2017

Why do you have to make it so complicated when you can simply do this,

[required]="isFieldRequired() ? 'required' : null"