加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

使用Angular 2 Forms动态标记字段的正确方法是什么?

发布时间:2020-12-17 17:56:41 所属栏目:安全 来源:网络整理
导读:使用Angular 2(2.0.0),使用 Angular Forms动态标记字段的建议方法是什么? 在他们的所有示例中,只添加了必需的属性,如: input type="text" class="form-control" id="name" required 如果我绑定的模型具有IsRequired属性,那将是真/假? 如果我使用类似的东
使用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”)时,它似乎不会识别此属性,所以当此字段为空时,我的表单本身仍然有效:

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

因此看起来我必须使用required而不是required =“true”,但是如何动态添加该属性?

什么也行不通:

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

以为我可能有一个函数可以根据字段返回我的字符串“required”,这只会产生模板错误.

有没有办法完成这个并只渲染我的属性需要?还是一种让Angular在值为true / false时识别此属性的方法?

FWIW – 我已经确认我可以使用* ngIf写两个近似相同的< input type ='text'/>基于我的IsRequired属性控制并使用所需属性对其进行硬编码,但这看起来很糟糕.希望有更好的方法!

解决方法

基本表单的内容非常适合简单的表单,但是当你需要更多的控件时,就像你需要开始使用更高级的表单一样.在你的情况下看起来会是这样的.

@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.

还有另一种方法可以使用here所示的指令来完成此操作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读