Issue
I am using an Observable on my form to get the data which looks like this on the template side.
<form *ngIf="menuData$ | async as menuData; else loading" [formGroup]="form">
This works great and i can access all fields in my data from the API. Problem that i am facing now is what to do when I want to use this form to create a new record. In that case there is no menuData$ which means my form never displays the fields. What is the best or correct way to handle this ?
here is the code i use for the observable
loadData(docId: string) {
console.log('We are loading Data for Doc : ' + docId);
this.menuParents$ = this.menuService.fetchMenuParents().pipe(
tap(parents => console.log(parents))
)
this.menuData$ = this.menuService.fetchMenuItem(docId).pipe(
tap(menuData => this.form.patchValue(menuData)),
tap(menuData => this.form.controls['DocId'].patchValue(menuData._type + '::' + menuData._id) )
)
this.saveBttn = 'Update'}
On the template I just bind the controls to the form which is reactive and is patch after the observable returns data
Solution
In your component TS:
@Input() mode = 'add'; // or 'edit'
In your template:
<form *ngIf="(mode === 'add' || (menuData$ | async as menuData)); else loading" [formGroup]="form">
Answered By - wlf
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.