Reputation: 146
I'm using a reactive form in order to register products in an Angular 8 SPA. I would like to reuse this same form, so once I click on update button, same form it's called (it's on a separate component), and that form will contain actual product data filled on it.
I don't know how to call the component and pass the actual product data to be edited, or better than that, the component to be able to distinguish when it's called for creating or updating an existing product.
This is the actual code that manages storing a new product:
submit() {
const selectedSubProducts = this.form.value.subproducts
.map((v, i) => v ? this.subproductsData[i]['id'] : null)
.filter(v => v !== null);
this.product = {
name: this.form.controls['name'].value,
subproducts: selectedSubProducts
};
this.is.addProduct(this.product);
this.form.reset();
}
UPDATE:
Forgot to say that the form is embedded in a modal using ng-bootstrap. So, the button that triggers the modal is in a component GridProductComponent
, that calls a ProductModalComponent
, that wraps the FormProductComponent
. So to send the actual product data I must traverse all of three components, no idea how to do that, or if it exists another clearer/easier approach.
<!-- part of GridProductComponent: -->
<td>
<button class="btn btn-primary"(click)="updateProduct(product, i)">
Update
</button>
</td>
<td>
<button class="btn btn-danger (click)="delProduct(product)">
Remove
</button>
</td>
<!-- ProductModalComponent template: -->
<app-modal title="{{ title }}">
<app-formproduct></app-formproduct>
</app-modal>
Upvotes: 3
Views: 1384
Reputation: 1996
you can prefill the form if it's selected for editing. The data can come from the click as input or get the data from the backend using the id param in your route. You need to have two separate routes for adding and editing using the same component.
fillForm(){
this.form.patchValue({
name: "name"
});
}
To check whether it's chosen for editing, you can take the URL id, if Id exists, then it's chosen for editing. If your route has a param "id" in your route for editing:
if (this.route.snapshot.params.id){
this.fillForm();
}
Don't forget to inject route of type ActivatedRoute
Upvotes: 3