Angular 角度反应形式-*Ng表示错误,而不是多个';否则';html中的语句

Angular 角度反应形式-*Ng表示错误,而不是多个';否则';html中的语句,angular,angular-forms,angular4-forms,Angular,Angular Forms,Angular4 Forms,我能找到的反应式表单验证错误消息的唯一示例是在HTML中以条件形式输出每个表单标签和每个错误消息 <span *ngIf="form.controls['exampleelement'].hasError('required') && form.controls['exampleelement'].touched" class="login-error">You must include a element.</span> <span *ngIf="

我能找到的反应式表单验证错误消息的唯一示例是在HTML中以条件形式输出每个表单标签和每个错误消息

<span *ngIf="form.controls['exampleelement'].hasError('required') && form.controls['exampleelement'].touched" class="login-error">You must include a element.</span>
<span *ngIf="form.controls['exampleelement'].hasError('minlength') && form.controls['exampleelement'].touched" class="login-error">Your element must be at least 20 characters .</span>
<span *ngIf="form.controls['exampleelement'].hasError('maxlength') && form.controls['exampleelement'].touched" class="login-error">Your element cannot exceed 20 characters .</span>

我认为这样做对你来说并不容易。我已经实现了你的要求,看看是否对你有帮助

我添加了以下组件变量:

formControlKeys = [];
errorMessages = {};
在构造函数中:

// initalized the form and then..

this.formControlKeys = Object.keys(this.subscriptionForm.controls);

this.errorMessages = {
  required: "You must include a element.",
  max: "Max allowed value for input is 10",
  min: "Min allowed value for input is 4"
}
并添加了一个类方法:

getObjectKeys(arg) {
  return Object.keys(arg);
}
然后在模板中:(有两个循环,一个循环表单中的所有表单控件,另一个循环每个控件中的所有错误)


{{errorMessages[eachError]}}

查看工作情况。

请查看更新的答案,我错过了对
触摸的检查
@Kravitz:是的,我看到了,链接没有打开,我也更新了链接,它仍然没有为您打开吗?
getObjectKeys(arg) {
  return Object.keys(arg);
}
<ng-container *ngFor="let eachControl of formControlKeys">
    <ng-container *ngIf="subscriptionForm.controls[eachControl].touched">
      <span *ngFor="let eachError of (getObjectKeys(subscriptionForm.controls[eachControl].errors))">
      {{errorMessages[eachError]}}<br>
      </span>
    </ng-container> 
 </ng-container>