web-dave / angular-essentials-workshop

2 stars 0 forks source link

Create a Book #16

Open web-dave opened 2 years ago

web-dave commented 2 years ago
web-dave commented 2 years ago
books-routing.module.ts ```ts { path: 'new', component: BookNewComponent } ```
books/book-list.component.html ```html NEW ```
books.module.ts ```ts import { ReactiveFormsModule } from '@angular/forms'; import ... @NgModule({ imports: [ CommonModule, BooksRoutingModule, ReactiveFormsModule ], exports: [], declarations: [...], providers: [] }) export class BooksModule { } ```
indexd Forme Type (angular 14+) ```ts export type IForm = { [K in keyof T]: FormControl; }; ```
book-new.component.ts (angular 14+) ```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.nonNullable.group({ title: ['', [Validators.required, Validators.minLength(6)]], isbn: ['', [Validators.required, Validators.minLength(6)]], id: ['', []], subtitle: ['', []], abstract: ['', []], author: ['', []], publisher: ['', []], price: ['', []], numPages: [0, []], cover: ['', []], userId: [0, []], }); } } ```
book-new.component.ts (angular <14) ```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.required, Validators.minLength(6)]], isbn: ['', [Validators.required, Validators.minLength(6)]], id: ['', []], subtitle: ['', []], abstract: ['', []], author: ['', []], publisher: ['', []], price: ['', []], numPages: [0, []], cover: ['', []], userId: [0, []], }); } } ```
books/book-new.component.html ```html
Enter a title
Not a valid ISBN
```
books.service.ts ```ts createBook(book): Observable { const url = `${this.restRoot}`; return this.http.post(url, book); } ```
book-new.component.ts ```ts saveBook() { this.bookService.createBook(this.form.getRawValue()).subscribe(); } ```
web-dave commented 2 years ago

Next