In my Angular 2 bookstore application, I have a method called selectedBook(b: Books)
within the BookComponent.
As the program runs, a table displays a list of books with each book having its own "Add to cart" button.
When the Add to cart button is clicked, the
selectedBook(b: Books)
method is invoked and the selected book is passed as a parameter.- The method should add the book to the
cartArray
(which is an array of Books model) only if it's not already in the cart. - When adding to the cart, if a duplicate book has its quantity decremented in the table view, it should increment in the
cartArray
(implementation pending).
books.model :
export interface Books {
id: number,
bookId: string,
bookName: string,
bookQuantity: number,
bookPrice: string,
bookAuthor: string,
bookPublished: string
}
selectedBook(b: Books)
Method Logic:
- The method decrements the quantity of the selected book and adds it to the cart for the first selection.
- For subsequent selections, the method checks if the book with the same
bookId
exists in the cart. If found, it setsduplicateBook
flag totrue
; otherwise, it adds the book to the cart. - Finally, the contents of the
cartArray
are stored in local storage.
BookComponent :
import {Component} from 'angular2/core';
import {Books} from '../models/books.model';
@Component({
selector: 'book',
templateUrl: `
<table class="table table-hover">
<tr>
<th>ID</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Author</th>
<th>Publisher</th>
<th>Actions</th>
</tr>
<tr *ngFor="#b of books">
<td><a>{{ b.bookId }}</a></td>
<td>{{ b.bookName }}</td>
<td>{{ b.bookQuantity }}</td>
<td>{{ b.bookPrice }}</td>
<td>{{ b.bookAuthor }}</td>
<td>{{ b.bookPublished }}</td>
<td>
<button type="button" class="btn btn-primary" *ngIf="b.bookQuantity > 0" (click)="selectedBook(b)">Add to cart</button>
<div *ngIf="b.bookQuantity < 1">Out of stock</div>
</td>
</tr>
</table>
`
})
export class BooksComponent {
books: Books[] = [
{ id: 1, bookId: '1', bookName: 'C', bookQuantity: 7, bookPrice: '2345', bookAuthor: 'fsdf', bookPublished: 'edsdf' },
{ id: 2, bookId: '2', bookName: 'Java', bookQuantity: 52, bookPrice: '3242', bookAuthor: 'sdfs', bookPublished: 'fghzxdffv' },
{ id: 3, bookId: '3', bookName: 'SQL', bookQuantity: 7, bookPrice: '5645', bookAuthor: 'dfghrty', bookPublished: 'ghjghj' }
];
cart: Books[] = [];
duplicateBook: boolean = false;
selectedBook(b: Books)
{
b.bookQuantity = b.bookQuantity - 1;
if (this.cart.length == 0) {
this.cart.push(b);
}
else {
for (let e of this.cart) {
console.log(e.bookId, "==", b.bookId);
if (e.bookId == b.bookId) {
console.log("Book is in cart");
this.duplicateBook = true;
break;
}
}
if (!this.duplicateBook) {
this.cart.push(b);
}
}
localStorage.clear();
localStorage.setItem('cartItems', JSON.stringify(this.cart));
console.log("Cart contents are : ", this.cart);
}
}