Angular2验证并在视图中显示错误

时间:2022-04-24 11:46:06

I am using Angular2 and Java for standalone back-end in my web project.

我在我的Web项目中使用Angular2和Java作为独立后端。

I have validation handling in back-end. If I press, for example - save button, http call occurs to back-end (where my data is validated), and returns response as json which contains validation error metadata (or empty).

我在后端进行验证处理。如果我按下,例如 - 保存按钮,http调用发生在后端(我的数据被验证),并返回响应为json,其中包含验证错误元数据(或空)。

Now I want to show those errors to my angular2 view (for email and name). How can I do that?

现在我想将这些错误显示在我的angular2视图中(对于电子邮件和名称)。我怎样才能做到这一点?

        @Component({
selector: 'my-selector',
templateUrl: `
 <label for="name">Name</label>
 <input  id="name" [(ngModel)]="name" />
  <div>space for error message</div>
  <label for="email">Email</label>
   <input  id="email"  [(ngModel)]="email" />
 <div >space for error message</div>
  <button (click)="onSave()"> Save </button>`  })

      export class EmailForm { 
        private name:string;
        private email:string;
        private errorMessages
    public onSave() {
        return this._deService.add(.....);
    }}
  //and I have validationErrorMessages for that input,recived from back-end,let already deserialized form
     let messages: ErrorMeta[] = [
     { validatorKey:'required', message:'Required',controlId:'name'},
     { validatorKey: 'invalidEmailAddress',message:  'Invalid email address',controlId:'email'}
     ];

1 个解决方案

#1


1  

update

getErrors(controlId) {
  return this.messages.filter(err => err.controlId == controlId);
}
<label for="name">Name</label>
<input  id="name" [(ngModel)]="name" [class.invalid]="getErrors('name').length"/>

<div *ngFor="let err in getErrors('name')">
  {{err.validatorKey}} - {{err.message}}
</div>

<div>space for error message</div>
<label for="email">Email</label>

<div *ngFor="let err in getErrors('email')">
  {{err.validatorKey}} - {{err.message}}
</div>

<input  id="email"  [(ngModel)]="email" />
<div >space for error message</div>

<div *ngFor="let err in getErrors('email')">
  {{err.validatorKey}} - {{err.message}}
</div>

<button (click)="onSave()"> Save </button>

#1


1  

update

getErrors(controlId) {
  return this.messages.filter(err => err.controlId == controlId);
}
<label for="name">Name</label>
<input  id="name" [(ngModel)]="name" [class.invalid]="getErrors('name').length"/>

<div *ngFor="let err in getErrors('name')">
  {{err.validatorKey}} - {{err.message}}
</div>

<div>space for error message</div>
<label for="email">Email</label>

<div *ngFor="let err in getErrors('email')">
  {{err.validatorKey}} - {{err.message}}
</div>

<input  id="email"  [(ngModel)]="email" />
<div >space for error message</div>

<div *ngFor="let err in getErrors('email')">
  {{err.validatorKey}} - {{err.message}}
</div>

<button (click)="onSave()"> Save </button>