typescript - Angular2 Update View After Form Submission -


i'm creating simple crud application using angular2. app consists of table list current records , form submit new records. what's correct way update table reflect new record after submit form? here's have far.

export class personform {   data: object;   loading: boolean;    personform: controlgroup;   constructor(private _peopleservice: peopleservice, personformbuilder: formbuilder) {     this.personform = personformbuilder.group({       'name': [],       'age': []     });   }    onsubmit(values:any) : void {     console.log(values);     this._peopleservice.createperson(values).subscribe()   } } 

in above, i'm assuming .subscribe() you'll handle callback update view?

and here's view:

<h1>people</h1>   <table class="ui celled small table ">     <thead>       <tr>         <th>name</th>         <th>age</th>       </tr>     </thead>     <tr *ngfor="#person of people">       <td>         {{person.name}}       </td>         <td>         {{person.age}}       </td>     </tr>   </table> <div> <person-form></person-form> </div> 

and here's form:

<form [ngformmodel]="personform"(ngsubmit)="onsubmit(personform.value)" class="ui form">    <div class="field">     <label>full name</label>     <input id="nameinput" type="text" placeholder="full name" [ngformcontrol]="personform.controls['name']">   </div>    <div class="field">     <label>age</label>     <input id= "ageinput" type="text" placeholder="age" [ngformcontrol]="personform.controls['age']">   </div>    <button type="submit" class="ui button blue">submit</button> </form> 

in view's component need set event listener. let's call personcomponent since don't know you've called it.

export class personcomponent{     person = {};      updateperson(person){         this.person = person;     } } 

then in personform need set eventemitter

export class personform {     data: object;     loading: boolean;     personupdated: eventemitter<any> = new eventemitter<any>();      ...      onsubmit(values:any) : void {         console.log(values);         this._peopleservice.createperson(values).subscribe((person) => {             this.personupdated.emit(person);         });     } } 

finally you'll subscribe event in personcomponent listen personupdated event , run updateperson method value of event.

<person-form (personupdated)="updateperson($event)"></person-form> 

Comments

Popular posts from this blog

shader - OpenGL Shadow Map -

stringtemplate - StringTemplate4 if conditional with length -