我在我的Web项目中使用Angular2和Java作为独立后端。
我在后端进行验证处理。如果我按下,例如 - 保存按钮,http调用发生在后端(我的数据被验证),并返回响应为json,其中包含验证错误元数据(或空)。
现在我想将这些错误显示在我的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'}
];
答案 0 :(得分:1)
<强>更新强>
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>