Skip to content

Data write

Expected state of the application after completing the "Bidirectional binding" section: [get code]

Our application can perform almost any function of the four basic ones, namely: data download, data update and deletion of selected elements. We only have to create new ones. Let's add the appropriate fields below the list of all students. To do this, open the file src/app/students/students.component.html and add:

<div class="new-student">
  <h2>Add a new student</h2>
  <label for="name">Name and surname:</label>
  <input type="text" id="name" #name>

  <label for="email">E-mail address:</label>
  <input type="email" id="email" #email>

  <button (click)="add(name.value, email.value); name.value=''; email.value=''">Dodaj</button>
</div>

In the above code, we declared the reference to the fields with the hash symbol #. For example, # name declares aname variable on the <input> element.

In response to the click event, add the add () method to the students.component.ts file, which will handle two parameters:name.value and email.value, which contain the value entered by the user in the reference fields. Additionally, after calling this method, we clear the value of both fields entered so far, so that we can add a new student.

Add the following method to the StudentsComponent class:

add(name: string, email: string): void {
  // Removing white characters from the data
  name = name.trim();
  email = email.trim();

  // Cease execution when fields are empty
  if (!name || !email) {
    return;
  }

  // Cease execution when e-mail address does not contain "@"
  if (email.indexOf('@') < 1) {
    return;
  }

  // Upload data to server and update local table
  this.studentService.addStudent({ name, email } as Student)
    .subscribe(student=> {
      this.students.push(student);
    });
}

When the given name and email are not empty, the application creates an almost complete student object, only missing the identifier, and passes it to the service method addStudent().

Upon successful saving, the subscribe() callback receives the new student from the server and places it on the list.

Final application status: get code.