Angular-是否将表单字段验证规则(例如firstname.dirty)放入TypeScript数组



如何将表单字段验证规则存储到数组中?我该用什么来代替"这里"?

formfields:  Array<Object> = [
    {label: "Employer:", control: "employer", validations: "{requirederror: "employer.errors?.required && employer.dirty", notvaliderror: "employer.errors?.maxlength && employer.dirty"}"},
    {label: "Phone:",    control: "phone",    validations: "{requirederror: "phone.errors?.required && phone.dirty", notvaliderror: "phone.errors?.pattern && phone.dirty"},
    {label: "Email:",    control: "email",    validations: "{requirederror: "email.errors?.required && email.dirty", notvaliderror: "email.errors?.email && email.dirty"}"}
];
<div *ngFor="let formfield of formfields; let i = index">
     <div class="labelandinput">
          <label class="label">{{formfield.label}}</label>
          <input class="input" formControlName="{{formfield.control}}">
          <div class="formfielderror" *ngIf=" /'''''HERE'''''/ ">...</div>
          <div class="formfielderror" *ngIf=" /'''''HERE'''''/ ">...</div>
     </div>
</div>

这么简单吗?

  <div class="formfielderror" *ngIf="{{formfield.validations.requirederror}}"> SOME REQUIRED ERROR </div>
  <div class="formfielderror" *ngIf="{{formfield.validations.notvaliderror}}"> SOME NOT VALID ERROR </div>

您应该重新思考如何引用数据。通常数组表示一组相似的项,每个项都可以是一个javascript对象,描述一个项。

假设您使用的是被动形式。也就是说,你的阵列在某种程度上看起来像

myItems = [
 formBulder.group({
   firstname: ['',[Validators.required(), Validators.pattern(/[0-9]+/)]],
   hobby: [''] // no validators here
 })
]

然后你可以用这个标记来渲染它

<div *ngFor="let item of myItems" [formGroup]="item">
  <input type="text" formControlName="firstName">
 <div *ngIf="item.firstName.errors?.required">firstname is required. please fill it</div>
 <div *ngIf="item.firstName.errors?.pattern">firstname should follow [0-9]+ pattern</div>
  
  <input type="text" formControlName="hobby">
</div>

希望这个例子足以让你开始学习。

如果一个项目只需要一个表单,则不需要数组。只要form = formBuilder.group({...})就足够了,并且不需要在模板中迭代*ngFor

相关内容

  • 没有找到相关文章

最新更新