gpt4 book ai didi

angular - 重用 Angular 8 响应式表单来创建/更新产品

转载 作者:行者123 更新时间:2023-12-04 15:35:54 25 4
gpt4 key购买 nike

我使用响应式表单在 Angular 8 SPA 中注册产品。我想重复使用同一个表单,所以一旦我点击更新按钮,就会调用同一个表单(它在一个单独的组件上),并且该表单将包含填写在上面的实际产品数据。

我不知道如何调用该组件并传递要编辑的实际产品数据,或者更好的是,该组件能够区分何时调用它来创建或更新现有产品。

这是管理存储新产品的实际代码:

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();
}

更新:

忘了说表单是使用 ng-bootstrap 嵌入到模态中的。因此,触发模态的按钮位于组件 GridProductComponent 中,该组件调用包装 FormProductComponentProductModalComponent。因此,要发送实际产品数据,我必须遍历所有三个组件,不知道该怎么做,或者是否存在另一种更清晰/更简单的方法。

<!-- 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>

最佳答案

如果选择编辑表单,您可以预填表单。数据可以来自作为输入的点击,也可以使用路由中的 id 参数从后端获取数据。您需要有两个单独的路由来使用同一组件进行添加和编辑。

fillForm(){
this.form.patchValue({
name: "name"
});
}

查看是否选择编辑,可以通过URL id获取,如果存在则选择编辑。如果您的路线在您的 route 有一个参数“id”用于编辑:

if (this.route.snapshot.params.id){
this.fillForm();
}

不要忘记注入(inject) ActivatedRoute 类型的路由

关于angular - 重用 Angular 8 响应式表单来创建/更新产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59769203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com