我有一个 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/