Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 558
lhan Avatar asked Oct 17 '16 19:10

lhan


People also ask

Which method is used to add dynamic validation to the forms in angular?

The FormGroup class exposes an API that enables us to set validators dynamically. We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.

How do you make a field mandatory in a form?

Summary: Using an asterisk to mark required fields is an easy way to improve the usability of your forms. Only marking optional fields makes it difficult for people to fill out the form.


2 Answers

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

[required]="isFieldRequired() ? 'required' : null"
like image 104
Edison D'souza Avatar answered Oct 09 '22 08:10

Edison D'souza


The basic forms stuff is great for simple forms, but when you need more control like what you have here, that is when you need to start using the more advanced form stuff. What that would look like in your case would be something like this.

@Component({
  selector: 'something',
  template: `
  <form #myForm="ngForm">
    <input [(ngModel)]="field.Value" [formContol]="myFieldControl" type="text" [value]="field.Value">
  </form>
  `
})
export class MyComponent{
  public field: any = {Value: 'hello', isRequired: false};
  public myFieldControl: FormControl = new FormControl('', [this.dynamicRequiredValidator.bind(this)]);

  public dynamicRequiredValidator(control: FormControl):{[key: string]: boolean}{
    if(field.IsRequired && !control.value){
      return {required: true};
    }
    return {};
  }
}

Note: You will probably need to import the ReactiveFormsModule into your @NgModule. This comes from @angular/forms as well.

There is also another way you can do this with a directive shown here.

like image 22
SnareChops Avatar answered Oct 09 '22 08:10

SnareChops