Lab 11: Reactive Forms
Objectives
- Create an add album form
Tasks
Task 1: Make the form
We have ou AlbumAddComponent let's create a form using the ReactiveForm approach.
-
import
ReactiveFormModulein yourapp.module.ts -
inject
FormBuilderandAlbumService -
Create a
FormGroupwith all the field required appartid.- Use the
FormBuilerand add somerequiredvalidators
- Use the
-
Create the HTML form using
FormGroupandformControlNameAttributes. -
Display errors in case some fields are missing.
-
On submit, we want to post our album in our rest API
-
Once the insert is done, we want to redirect to the album detail
[HINT] Don't forget to subscribe to the
Observablethat come from your service! You can redirect to the album list once it have been inserted.
Task 2: Display the album details
- We have seen that our album have a generated id that take the form of a string.
- We then, have en error if we try to navigate to the new element using previous or next item button in the
AlbumDetailComponent - Normally we would create a backend method to give us the next or previous album but we dont have such a feature. we need to find a strategy to do it on our own!
Strategy:
- When we fetch our albums we can set an array with all IDs so we can use that to know where to navigate first, you could also set all the albums in a array but using the ID strategy would allow us to always fetch the latest version of our object.
`album.service.ts``
- Add
ids: string[] = []; - Modify the
album.model.tsidto be astring - You will have to correct errors in your
album-static.service.ts - Let's now modify our
getAllmethod so it can store all ids in a array.
getAll(): Observable<Album[]>{
return this.http.get<Album[]>(this.serverUrl).pipe(
map(albums => {
this.ids = albums.map(a => a.id);
return albums;
})
);
}
- add the
nextIdandprevIdmethod
// Example with nextId
nextId(id: string): string{
const index = this.ids.indexOf(id);
if (index === this.ids.length - 1){
return this.ids[0];
}
return this.ids[index + 1];
}
Also need to change the parameters in all methods from number to string.
// example:
get(id: string): Observable<Album>{
album-detail.component.ts
- In the
ngOnInit, load all albums ids if they are not loaded yet
if(this.albumService.ids.length === 0){
this.albumService.getAll().subscribe()
}
- Later in the code, change the cast from Number to String
- Call the new methods