Improving the book list component

To finish our upgrade to Angular Material, we'll work on the book-list component.

In this case, we will use the following Angular Material components: mat-button, mat-table, and mat-icon.

Open the controller (that is, src/app/book/components/book-list/book-list.component.ts) and add the following public field to the class:

public displayedColumns: string[] = [ 
    'pictureLocation', 'name', 'genre', 'description', 'author', 
'numberOfPages', 'identifier' ];

This field will be used by the mat-table component to identify the columns that should be displayed or hidden.

Now, adapt the template of the component, as follows:

<table mat-table [dataSource]="books" fxFlex> 
  <ng-container matColumnDef="pictureLocation"> 
    <th mat-header-cell *matHeaderCellDef>Picture</th> 
    <td mat-cell *matCellDef="let book"><img alt="picture" 
[src]="book.pictureLocation" class="mediaImage"></td> </ng-container> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef>Name</th> <td mat-cell *matCellDef="let book"> {{ book.name }} </td> </ng-container> <ng-container matColumnDef="genre"> <th mat-header-cell *matHeaderCellDef>Genre</th> <td mat-cell *matCellDef="let book"> {{ book.genre }} </td> </ng-container> <ng-container matColumnDef="description"> <th mat-header-cell *matHeaderCellDef>Description</th> <td mat-cell *matCellDef="let book"> {{ book.description }} </td> </ng-container> <ng-container matColumnDef="author"> <th mat-header-cell *matHeaderCellDef>Author</th> <td mat-cell *matCellDef="let book"> {{ book.author }} </td> </ng-container> <ng-container matColumnDef="numberOfPages"> <th mat-header-cell *matHeaderCellDef>Pages</th> <td mat-cell *matCellDef="let book"> {{ book.numberOfPages }} </td> </ng-container> <ng-container matColumnDef="identifier"> <th mat-header-cell *matHeaderCellDef>Remove</th> <td mat-cell *matCellDef="let book"> <button mat-icon-button color="warn"
(click)="removeBook(book.identifier)"> <mat-icon>cancel</mat-icon> </button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table>

As you can see, creating a Material table is easy:

  1. First, we defined a simple HTML table.
  2. Then, we added the mat-table directive to it.
  3. After that, we added a binding defining the data source for the table with [dataSource]="books".
  4. Then, for each column in our table, we defined an ng-container element, wrapping th and td elements and using other Angular Material directives.