Allow me to use a well-known book example to illustrate my query. I have created an Angular Material reactive form based on the Book Model in my BookService.ts. However, when I modify certain fields in this form and attempt to submit it to update the corresponding record in my database using the Angular HttpClient PUT method, I encounter an error. Upon debugging, it appears that the ID is not defined. When I console.log(BookForm.value)
, the output I receive is:
{$key: 1234, Title: "Book Title1", Topic: "Topic1"}
. It goes without saying that my Angular HttpClient PUT Restful API requires the ID to be able to update that specific record in my Database table. Below is a simplified mocked code snippet to clarify the issue.
BookModel.ts File, My Model
export interface Book{
ID: number;
Title: string;
Topic: string;
}
BookService.ts File, My Service
BookForm: FormGroup = new FormGroup({
$key: new FormControl(null),
Title: new FormControl('', Validators.required),
Topic: new FormControl('', Validators.required),
});
UpdateBook(bookObj: Book): Observable<Book>
{
return this.http.put<Book>(`...api/book/${bookObj.ID}`, bookObj,{
headers: new HttpHeaders({
'Content-Type: 'application/json'
})
})
}
Note: This Throws Error, ID Undefined
Book-form.component.html File
<form [formGroup] = "BookService.BookForm" class="FormCls">
<mat-grid-list rowHeight="200px">
<mat-grid-tile>
<div class="form-controles-container">
<input type="hidden" formControlName="$key" />
<mat-form-field>
<input formControlName="Title" matInput placeholder="Title*" />
<mat-error>Title Needed</mat-error>
</mat-form-field>
<mat-form-field>
<input formControlName="Topic" matInput placeholder="Topic*" />
<mat-error>Topic Needed</mat-error>
</mat-form-field>
<div class="button-row">
<button mat-raised-button color="primary" type="submit" (click)="onSubmit()">Submit</button>
</div>
</div>
</mat-grid-tile>
</mat-grid-list>
</form>
Book-form.component.ts File
onSubmit(): void
{
BookService.UpdateBook(BookService.BookForm.value).subscribe(
b => alert(`Book Updated Successfully`),
err => alert(`Exception While Updating: ${err}`)
);
}
I am aware that I need to somehow convert my form value to match my Book model and ensure that the ID is included before passing it to my HTTP put service. However, being relatively new to both Angular and Typescript, I am unsure how to accomplish this. I prefer to research before seeking help, so I have read numerous articles but none have provided a solution. For instance, I attempted the article on stackoverflow linked below but it did not work for me: Reactive Forms correctly convert Form Value to Model Object
I greatly appreciate the assistance from experienced professionals and thank you for taking the time to help.