Reputation: 2195
I'm creating a simple CRUD application using Angular2. The app consists of a table to list current records and a form to submit new records. What's the correct way to update my table to reflect the new record after I submit the form? Here's what I have so 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 the above, I'm assuming .subscribe()
is where you'll handle the callback to update the view?
And here's that 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 the 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>
Upvotes: 4
Views: 3027
Reputation: 13347
In your view's component you will need to set an event listener. Let's call that PersonComponent
for now since I don't know what you've called it.
export class PersonComponent{
person = {};
updatePerson(person){
this.person = person;
}
}
Then in your PersonForm
you will need to set an 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 to the event in you PersonComponent
which will listen to the personUpdated
event and run the updatePerson
method with the value of that event.
<person-form (personUpdated)="updatePerson($event)"></person-form>
Upvotes: 3