validation - Angular 4 bind HTTP response to typescript model -
i have angular 4 page gets inputs user. have validation on individual controls. on submit want server validations (essentially rechecking validations) , return errors array field name, true or false , error if failed.
i these errors map controls on page , show errors. using reactive forms , server response use same name form control.
example, control name 'name'. after submit response name invalid. show , error message under control. mvc when upon submit errors shown next each control.
is possible , how go generating generic binding used forms.
yes, quite simple in angular. here example how so. 1. html file. <form [formgroup]="saveform" (ngsubmit)="savedata()" > <div> <label>name</label> <input id="name" type="text" class="form-control" formcontrolname="name" tabindex="1"> </div> <div *ngif="errror" > <p>{{errormsg}}</p> </div> <button type="submit" id="btnsave" >save</button> </form> 2.in component ts. a. defined formgroup & error message variable. saveform :formgroup; errror :boolean = false ; errormsg :any; b. initialize form group. (you can defined client side validation here using angular validator) this.saveform = this.fb.group({ name: [''] }); c. on save data method need set error bit true. savedata() { let data = this.saveform .value.name; this._userservice.save(data) // calling service here. .subscribe( (response :any )=> { console.log(response); } }, (error :any ) => { this.error = true; this.errormsg = error.error; // assigning server side errro variable. } ); } that's done.
Comments
Post a Comment