web-dave/angular-starter-v2

edit a book

Opened this issue · 7 comments

  • Generate a book-edit component
  • Add a edit route
  • Import FormsModule into BooksModule
  • Bind book to a template driven form
  • extend the service to save edited book

generate

  ng g c books/book-edit
books-routing.module.ts
    {
      path: ':isbn/edit',
      component: BookEditComponent
    }
book-details.component.html
<a [routerLink]="['edit']" class="btn btn-default btn-sm">
    <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</a>
books.module.ts
  import { FormsModule } from '@angular/forms';

  import ...

  @NgModule({
  imports: [
    CommonModule,
    BooksRoutingModule,
    FormsModule
  ],
  exports: [],
  declarations: [...],
  providers: [...]
  })
  export class BooksModule { }
books/book-edit.component.html
  <form *ngIf="book" #form="ngForm" (ngSubmit)="saveBook()">
    <div class="form-group">
        <label for="title">Title</label>
        <input 
          type="text" 
          id="title" 
          name="title" 
          required minlength="6" 
          [(ngModel)]="book.title" 
          #title="ngModel">
        <div [hidden]="!title.errors?.required || title.pristine">Enter a Title</div>
    </div>
      ...
    <div>
      <button type="submit" [disabled]="form.invalid">Save</button>
      <a class="btn btn-default btn-sm" [routerLink]="['..']">
    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
      </a>
    </div>

  </form>
books/book-edit.component.ts
  saveBook() {
    this.booksService.updateBook(this.book)
          .subscribe(() => {
            this.router.navigate(['..'],{relativeTo:this.route});
          });
  }
book.service.ts
  updateBook(book): Observable<IBook> {
    const url = `${this.restRoot}/${book.isbn}`;
    return this.http.patch<IBook>(url, book);
  }