web-dave / angular-starter-v2

6 stars 3 forks source link

Create a Book #19

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-new
web-dave commented 7 years ago

books-routing.module.ts


    {
      path: 'new',
      component: BookNewComponent
    }
web-dave commented 7 years ago
books/book-list.component.html

  <a [routerLink]="['new']" class="btn btn-default btn-sm">
    <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
  </a>
web-dave commented 7 years ago

books.module.ts


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

  import ...

  @NgModule({
  imports: [
    CommonModule,
    BooksRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ],
  exports: [],
  declarations: [...],
  providers: [...]
  })
  export class BooksModule { }
web-dave commented 7 years ago
books/book-new.component.ts

  import { Validators, FormBuilder, FormGroup } from '@angular/forms';
  @Component({
    selector: 'book-new',
    ...
  })
  export class BookNewComponent implements OnInit {
    form: FormGroup;
    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
      this.form = this.formBuilder.group({
        title: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
        isbn: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
        publisher: this.formBuilder.group({
          name: ['', Validators.required],
          url: ['', Validators.required]
        })
      });
    }

  }
web-dave commented 7 years ago
books/book-new.component.html

<form [formGroup]="form" (ngSubmit)="saveBook()">
  <div class="form-group">
    <label for="title">Title</label>
    <input type="text" id="title" formControlName="title">
    <div [hidden]="!form.get('title').hasError('required')">
      Enter a tilte
    </div>
  </div>
  <div class="form-group">

    <label for="isbn">ISBN</label>
    <input type="text" id="isbn" formControlName="isbn">
  </div>
  <fieldset formGroupName="publisher">
    <div class="form-group">
      <label>Name:</label>
      <input type="text" formControlName="name">
    </div>
    <div class="form-group">

      <label>Url:</label>
      <input type="text" formControlName="url">
    </div>

  </fieldset>

  <div [hidden]="!form.get('isbn').hasError('isbn')">
    Not a valid ISBN
  </div>

  <button type="submit" [disabled]="form.invalid">Save</button>
</form>
web-dave commented 7 years ago

books.service.ts


  createBook(book): Observable<IBook> {
    const url = `${this.restRoot}`;
    return this.http.post<IBook>(url, book);
  }