Update the "Model"

 Update the "Model" contact.component.ts file as follows:

import { FormBuilder, FormGroup } from '@angular/forms';
feedbackForm: FormGroup;
fb: Feedback;
private fbformbuilding: FormBuilder) {this.createForm(); }
createForm() {
this.feedbackForm = this.fbformbuilding.group({
firstname: '',
lastname: '',
message: ''
});
}
onSubmitFeedback() {
this.fb = this.feedbackForm.value;
console.log(this.fb);
this.feedbacks.push(this.fb);
this.feedbackForm.reset({
firstname: '',
lastname: '',
message: ''
});
}

Note

  • the import of { ... FormGroup } from '@angular/forms'; and 
  • the property in the component class named feedbackForm sets the property to an instance of the FormGroup

Using the FormBuilder we will create FormControl instances with the appropriate names firstName, lastName and message. FormBuilder is like a factory that creates FormGroups and FormControls for us.

Note 

  • the import of { FormBuilder ... } from '@angular/forms';
  • the injection of FormBuilder into the constructor of the Component : private fbformbuilding: FormBuilder. The FormBuilder is an injectable service that is provided with the ReactiveFormsModule

In order to create the feedbackForm model we use the fbformbuilding.group in the createForm() method. This way we create the formControlNames firstName, lastName and message as strings. Note how the fields within the form are the same as the fields within the Feedback class so the form model becomes a lot more straightforward. 

The individual form controls are now collected within a group. The FormGroup provides its model value as an object reduced from the values of each control in the group.
The FormGroup also tracks the status and changes of each of its controls, so if one of the control’s status or value changes, the parent control also emits a new status or value change. The model for the group is maintained by its members. In the next page, we will update the template to reflect the model in the view.

The onSubmitFeedback() method

Here we create a method called onSubmitFeedback() which when the user clicks the button, it will take the user's input and display it on the page.

  • To do this we apply the user's input taken from the this.feedbackForm.value to the this.fb property which is an instance of Feedback class.
  • Next, we push this information in the this.feedbacks array. This feedbacks array is already defined inside the view and already displays the information present in the db.json file. When we use push, we take the new value added and push it in this array as a new list-group- item under the existing items. 
  • Also, we use reset so that the feedbackForm values will reset to their initial values. 

Note that this procedure doesn't communicate with the server. Hence, on reload, the new submitted item will disappear.