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

半世苍凉 提交于 2021-02-07 13:16:43

问题


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!


回答1:


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.




回答2:


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

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


来源:https://stackoverflow.com/questions/40094435/what-is-the-proper-way-to-dynamically-mark-a-field-as-required-using-angular-2-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!