Create

Service

addStudent(firstName: string): Promise<void> {
    const itemCollection = collection(this.firestore, 'students');
    return addDoc(itemCollection, {
      firstName: firstName,
    }).then(() => {});
}

Component

onSubmit() {
    const firstNameValue = this.loginForm.get('firstName')?.value;
    if (!firstNameValue) {
      console.error('First name is required!');
      return;
    }
    if (this.isEditing && this.editingStudentId) {
      const studentId = '';
      this.studentService
        .editStudent(this.editingStudentId, firstNameValue)
        .then(() => {
          console.log('Edited student with ID: ' + studentId);
        });
      this.isEditing = false;
    } else {
      this.studentService.addStudent(firstNameValue);
    }
    this.onReset();
    this.isEditing = false;
}

Template

<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
  <div class="mb-3">
    <label for="firstName" class="form-label">First Name</label>
    <input
      formControlName="firstName"
      type="text"
      class="form-control"
      id="firstName"
    />
  </div>
  <div class="buttons">
    <button type="submit" class="btn btn-primary mr-3">Submit</button>
    <button *ngIf="isEditing" (click)="onCancel()" class="btn btn-dark">
      Cancel
    </button>
  </div>
</form>
Was this page helpful?