An Angular sample application to display a list of books.

An Angular sample application to display a list of books.
An Angular sample application to display a list of books.
An Angular sample application to display a list of books. 

Great! Let's create an Angular sample application to display a list of books with the ability to add new books to the list. We will also explain the code for each component, including the data model, services, and UI components.
Table of Contents

Prerequisites

Before we start, you should have the following tools installed:

Create a New Angular Project

Open your terminal and run the following command to create a new Angular project:

ng new bookstore

This command generates a new Angular project with the name "bookstore".

Create a Book Model

To represent books in our application, we will create a book model. In your terminal, navigate to the project directory and run the following command to create a new book model:

ng generate interface models/book

This command generates a new TypeScript interface for our Book model in the src/app/models directory.

Open src/app/models/book.ts and add the following properties to the interface:

export interface Book {
  id: number;
  title: string;
  author: string;
  description: string;
  imgUrl?: string;
}

Create a Book Service

To fetch and save books, we will create a book service. In your terminal, run the following command to create a new book service:

ng generate service services/book

This command generates a new TypeScript service for our Book service in the src/app/services directory.

Open src/app/services/book.service.ts and update the class with the following methods:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';

import { Book } from '../models/book';

@Injectable({
  providedIn: 'root'
})
export class BookService {
  private books: Book[] = [
    {
      id: 1,
      title: 'Angular Tutorial',
      author: 'John Smith',
      description: 'A beginner\'s tutorial on Angular',
      imgUrl: '/assets/images/angular-tutorial.png'
    },
    {
      id: 2,
      title: 'Angular Services',
      author: 'Jane Doe',
      description: 'Learn how to use services in Angular',
      imgUrl: '/assets/images/angular-services.png'
    }
  ];

  getBooks(): Observable<Book[]> {
    return of(this.books);
  }

  addBook(book: Book): void {
    this.books.push(book);
  }
}

The books property is an array of books that will be used to display the list of books in our UI. The getBooks method returns the array of books as an Observable. The addBook method adds a new book to the array.

Create a Book Component

To display the list of books and add new books to the list, we will create a book component. In your terminal, run the following command to create a new book component:

ng generate component components/book

This command generates a new TypeScript component for our Book component in the src/app/components directory.

Open src/app/components/book.component.ts and add the following code:

import { Component, OnInit } from '@angular/core';
import { Book } from '../models/book';
import { BookService } from '../services/book.service';

@Component({
  selector: 'app-book',
  templateUrl: './book.component.html',
  styleUrls: ['./book.component.css']
})
export class BookComponent implements OnInit {
  books: Book[] = [];
  newBook: Book = {} as Book;
  error: string = '';

  constructor(private bookService: BookService) {}

  ngOnInit(): void {
    this.getBooks();
  }

  getBooks(): void {
    this.bookService.getBooks()
      .subscribe(
        books => this.books = books,
        error => this.error = error
      );
  }

  addBook(): void {
    if (this.newBook.title.trim() && this.newBook.author.trim()) {
      this.newBook.id = this.books.length + 1;
      this.bookService.addBook(this.newBook);
      this.newBook = {} as Book;
      this.error = '';
    } else {
      this.error = 'Please provide book title and author';
    }
  }
}

The books property is an array of books that will be populated by the getBooks method. The newBook property represents the new book that will be added to the list. The error property is used to display any validation errors when adding a book.

The getBooks method calls the bookService.getBooks() method to populate the books array. The addBook method checks the validity of the provided book title and author, assigns a new id to the book, and adds it to the books array.

Create a Book UI Component

To render the list of books and the form to add a new book, we will create a book UI component. Open src/app/components/book.component.html and add the following HTML:

<div class="book-list">
  <h2>Book List</h2>
  
  <div *ngIf="error" class="error">{{ error }}</div>
  
  <div *ngIf="!books.length && !error" class="no-books">No books available</div>
  
  <div *ngFor="let book of books" class="book">
    <div>
      <img [src]="book.imgUrl" alt="book cover">
    </div>
    <div>
      <h3>{{ book.title }}</h3>
      <p>Author: {{ book.author }}</p>
      <p>Description: {{ book.description }}</p>
    </div>
  </div>
</div>

<div class="book-form">
  <h2>Add Book</h2>
  
  <form>
    <div>
      <label for="title">Title:</label>
      <input type="text" id="title" [(ngModel)]="newBook.title">
    </div>
    
    <div>
      <label for="author">Author:</label>
      <input type="text" id="author" [(ngModel)]="newBook.author">
    </div>
    
    <div>
      <label for="description">Description:</label>
      <textarea id="description" [(ngModel)]="newBook.description"></textarea>
    </div>
    
    <div>
      <label for="imgUrl">Image URL:</label>
      <input type="text" id="imgUrl" [(ngModel)]="newBook.imgUrl">
    </div>
    
    <div>
      <button type="button" (click)="addBook()">Add Book</button>
    </div>
  </form>
</div>

This HTML template displays the list of books as well as a form to add new books. It uses Angular's built-in structural directives - *ngIf and *ngFor - to conditionally render the UI elements.

Update the App Component

Finally, we need to update the app component to add the book component to our application. Open src/app/app.component.html and add the following HTML:

<app-book></app-book>

This code will render our BookComponent in the main view of the application.

Conclusion

You have built a simple Angular application to display a list of books with the ability to add new books to the list. You also learned how to create a data model, service, and UI components in Angular. As you continue to develop your Angular skills, you can build more complex applications using more advanced concepts such as routing, forms, and observables. The sky is the limit with Angular!




Hello! My name is Aniket Shahane and I am a senior software consultant. I hold a post-graduate degree (MTech) in Computer Science and Engineering, and I have a passion for using my technical experti…

Post a Comment

© Coding and programming. All rights reserved. Premium By Raushan Design