Create Component

Generate Component

Just like we did for the creation of the book list component, we will have to navigate to the directory we want our component to be created in.

cd src/app/applications/book-management-system/

Then we generate our component bms-add-book:

ng generate component bms-add-book

We also need to define the path of adding a book to our module.

//... 
const routes: Routes = [
  {
    path: "",
    component: BmsMainPageComponent
  },
  {
    path: "list",
    component: ListBooksComponent
  },
  {
    path: "add",
    component: BmsAddBookComponent
  }
];

Application Logic

Add a book

The code to add a book is rather simple. The user is presented with a form that needs to be filled out. This form contains information about the book (title, author and ISBN) as well as a submit button. Each filed has a corresponding ID. For instance the input field for the title of the book is identifying by bookTitle. We will see later why we need these IDs. We also want to add some styling to improve the looks of our form.

To be able to reference a bookForm, we first have to build a form and specify the fields that we want our form to hold.

//... imports
@Component({
  selector: 'app-bms-add-book',
  templateUrl: './bms-add-book.component.html',
  styleUrls: ['./bms-add-book.component.css']
})
export class BmsAddBookComponent implements OnInit {
  bookForm;
  bookAdded: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  constructor(private formBuilder: FormBuilder, private bmsService: BmsService,
   private router: Router) {
    this.bookForm = this.formBuilder.group({
      title: "",
      author: "",
      isbn: 0
    })
  }

  ngOnInit() {
  }
}

When a form is submitted, the function onSubmit() is called and it takes as an argument the value of the form bookForm.value.

As a matter of fact, when a book is submitted, all we need to do is to call the service responsible for adding a book with the information that was just submitted.

//...
onSubmit(book) {
  this.bookForm.reset();
  console.warn("Book Data:", book);
  this.bmsService.addBook(book);
  this.bookAdded.next(true);
}

In any good navigation design, the user should be able to intuitively navigate through the website. To achieve that, we have to offer the user a way through which they can access the add book component as well as exit it or go back to a previous component (book listing component).

Let us go back to the book list component that we have previously created and add a button that redirects the user to the route that we defined for our add book component.

//...
goToAdd() {
  this.router.navigate(["/apps/bms/add"])
}

Now, we can reach the add book component from the book listing component by simply clicking on the button "Add Book".

We also want to allow the user to go back to the book listing in case they miss-clicked or simply changed their mind.

//...
goBack() {
  this.router.navigate(["/apps/bms"])
}

Last updated