Skip to main content

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 ReactiveFormModule in your app.module.ts

  • inject FormBuilder and AlbumService

  • Create a FormGroup with all the field required appart id.

    • Use the FormBuiler and add some required validators
  • Create the HTML form using FormGroup and formControlName Attributes.

  • 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 Observable that 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.ts id to be a string
  • You will have to correct errors in your album-static.service.ts
  • Let's now modify our getAll method 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 nextId and prevId method
 // 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