10

使用 Angular 2 (2.0.0) ,使用Angular Forms根据需要动态标记字段的推荐方法是什么?

在他们所有的例子中,所需的属性只是添加如下:

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

如果我绑定的模型有一个IsRequired属性,那将是真/假?

如果我使用类似的东西:

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

这在页面上呈现(注意="true"):

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

出于某种原因,当 Angular 具有实际值( ="true" )时,Angular 似乎无法识别此属性,因此当此字段为空白时,我的表单本身仍然有效:

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

所以看起来我必须使用required而不是required="true",但我怎样才能动态添加该属性?

什么也不起作用:

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

以为我可能有一个函数可以根据字段返回我的字符串“必需”,这只会给出模板错误。

有没有办法做到这一点并只required为我的属性渲染?或者当它的值为真/假时让Angular识别这个属性的方法?

FWIW - 我已经验证我可以使用基于我的属性*ngIf编写两个几乎相同的控件并使用该属性对一个进行硬编码,但这看起来很hacky。希望有更好的方法!<input type='text' />IsRequiredrequired

4

2 回答 2

14

当你可以简单地做到这一点时,为什么还要让它变得如此复杂,

[required]="isFieldRequired() ? 'required' : null"
于 2017-09-08T06:47:50.447 回答
3

基本表单的东西非常适合简单的表单,但是当您需要像这里所拥有的那样进行更多控制时,那就是您需要开始使用更高级的表单东西的时候。在你的情况下看起来会是这样的。

@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 {};
  }
}

注意:您可能需要ReactiveFormsModule@NgModule. 这也来自于@angular/forms

还有另一种方法可以使用此处显示的指令执行此操作。

于 2016-10-17T20:11:10.157 回答