Reputation: 95
There are 2 components. In DashboardComponent
there is a list of created forms and in CreateFormComponent
, I need to perform add and edit operation on the created forms that are being displayed in the DashboardComponent
. Both the operations will use the same form.
I can navigate from the DashboardComponent
to the CreateFormComponent
according to a particular ID but not able to perform the edit operation on it.
Code:
dashboard.html
<tr
*ngFor="let user of users"
style="text-align: center;">
<button
mat-mini-fab
style="background: white !important;color:black !important;outline:none;"
[routerLink]="['/Create_form',user.id]">
<!--<i class="fa fa-edit" aria-hidden="true"></i>-->
Edit
</button>
</tr>
Create_Form:
<form
#spfForm="ngForm"
(ngSubmit)="createspf(spfForm.value)"
ngNativeValidate>
<mat-form-field style="margin-top:-6%;">
<mat-select
[(ngModel)]="Priority"
name="Priority"
placeholder="Priority">
<mat-option value="High">
High
</mat-option>
<mat-option value="Medium">
Medium
</mat-option>
<mat-option value="Low">
Low
</mat-option>
</mat-select>
</mat-form-field>
</form>
Create_form.component.ts:
createspf(value) {
this.userservice.spf(value).subscribe((res: Response) => [
this.IsAdded = true,
console.log(this.confirmationString)
]);
}
Upvotes: 2
Views: 5063
Reputation: 39482
Since you didn't really provide a StackBlitz and I'm not having the time to create a whole Form Stackblitz for you, here's what I suggest you do:
In your CreateFormComponent
, when in the ngOnInit()
, initialize a ReactiveForm, either using a FormBuilder
, or by manually creating one using FormGroup
and FormControls
.
Also inject ActivatedRoute
in this component and subscribe to activatedRouterInstance
's params
BehaviorSubject
. If there's any id
coming in from there, get the details of the item by that id and populate the form that you creted by calling setValue
or patchValue
on it.
In case of Create, since there won't be any id in the params, the user will only see an empty form. But in case of edit, since the value of the form would be achieved, the user will see the form filled with the achieved data.
Hope that makes some sense and helps you out.
Upvotes: 3