web-dave / Angular-Essentials-Training

9 stars 0 forks source link

Edit a Book #17

Open web-dave opened 6 years ago

web-dave commented 6 years ago
web-dave commented 6 years ago

generate

  ng g c books/book-edit
web-dave commented 6 years ago
books-routing.module.ts

    {
      path: ':isbn/edit',
      component: BookEditComponent
    }
web-dave commented 6 years ago
book-details.component.html
<a [routerLink]="['edit']" class="btn btn-default btn-sm">
    edit
</a>
web-dave commented 6 years ago
books.module.ts

  import { FormsModule } from '@angular/forms';

  import ...

  @NgModule({
  imports: [
    CommonModule,
    BooksRoutingModule,
    FormsModule
  ],
  exports: [],
  declarations: [...],
  providers: [...]
  })
  export class BooksModule { }
web-dave commented 6 years ago
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.valid">Save</button>
      <a class="btn btn-default btn-sm" [routerLink]="['..']">X</a>
    </div>

  </form>
web-dave commented 6 years ago
books/book-edit.component.ts

  saveBook() {
    this.booksService.updateBook(this.book)
          .subscribe(() => {
            this.router.navigate(['..'],{relativeTo:this.route});
          });
  }
web-dave commented 6 years ago
book.service.ts

  updateBook(book: IBook): Observable<IBook> {
    const url = `${this.restRoot}/${book.isbn}`;
    return this.http.put<IBook>(url, book);
  }
web-dave commented 6 years ago

Create a Book