Reputation: 758
I am using Angular2 and Java for standalone back-end in my web project.
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).
Now I want to show those errors to my angular2 view (for email and name). How can I do that?
@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'}
];
Upvotes: 0
Views: 195
Reputation: 657108
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>
Upvotes: 1