css - 根据 Angular 2 表单中分配的验证器标记必填字段的标签

标签 css forms validation angular

我有一个 Angular 2 表单,其中包含许多必填字段。这些已分配了 Validators.required 。我想向这些字段的标签添加星号。

<form [formGroup]="form">
   <div class="form-group row">
     <label class="col-sm-3 col-form-label">First Name -> Add asterisk here</label>
     <div class="col-sm-9">
       <input formControlName="firstName" type="text" class="form-control">
     </div>
   </div>
...

我用谷歌搜索并阅读了 docs ,但找不到此用例的实现。

我知道我可以手动添加所需的属性并从那里开始工作,但我宁愿避免,因为这对于验证器分配来说似乎是多余的。

最佳答案

不确定它是否是最好的ng2风格解决方案,但是这个怎么样:

让您的 FormComponent 保存一组必填字段。在您的模板中,您可以简单地使用如下内容:

<label for="firstName">
    FirstName <span *ngIf="isFieldRequired('firstName')"> *</span>
</label>

如果您不想通过模板重复代码,则可以为带星号的标签创建单独的组件,例如:

@Component({
  selector: 'my-label',
  template: `<label for="{{id}}">{{label}} <span *ngIf="isFieldRequired(id)"> *</span></label>`
})
export class MyLabelComponent {
  @Input() label: string;
  @Input() id: string;
  @Input() requires: [];
  constructor() { }

    isFieldRequired(id) {
      return this.requires.indexOf(id) !== -1; // check if the array contains the value
  }
}

在您的表单组件中,您只需将值传递给 my-label 组件,例如:

<my-label [requires]="requiredFields" [label]="'Name'" [id]="'name'"></my-label>

这是此示例的工作插件:http://plnkr.co/edit/M66IFQGhhe82mNt3ekxw?p=preview 以及如何将所需的定义与更多自定义验证器一起使用的想法。请参阅app.component.ts

关于css - 根据 Angular 2 表单中分配的验证器标记必填字段的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40721569/

相关文章:

forms - "Are you sure?"通过 powershell 中的消息框

html - 使用rvest或httr登录网页上的非标准表单

javascript - WTForms-Javascript : pass onclick to WTF field

javascript - 欧芹js : How to validate input fields inside Modal popup and display error messages inside the modal itself

ios - IOS 7中的电子邮件地址验证

jquery - facebook 应用样式 向下滚动时 Conceal 标题栏,向上滚动时再次显示

html - CSS 动画图像显示

html - 如何在 Vim 每次保存 "source file"时自动更新或压缩 CSS、JS 和 HTML 文件?

javascript - 如何暂停音轨?

forms - Bootstrap-vue with Vuelidate,如何在初始状态停止验证表单