web-dave / angular-starter-v2

6 stars 3 forks source link

edit a book #16

Open web-dave opened 7 years ago

web-dave commented 7 years ago
web-dave commented 7 years ago

generate

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

    {
      path: ':isbn/edit',
      component: BookEditComponent
    }
web-dave commented 7 years ago
book-details.component.html

<a [routerLink]="['edit']" class="btn btn-default btn-sm">
    <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</a>
web-dave commented 7 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 7 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.invalid">Save</button>
      <a class="btn btn-default btn-sm" [routerLink]="['..']">
    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
      </a>
    </div>

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

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

  updateBook(book): Observable<IBook> {
    const url = `${this.restRoot}/${book.isbn}`;
    return this.http.patch<IBook>(url, book);
  }