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

标签 angular

我使用响应式表单在 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/

相关文章:

css - 在 Angular 中导入全局 css 文件会导致 Webpack 发出巨大的模块包

javascript - 原始异常 : Cannot read property 'Value' of undefined

javascript - Angular 通配符路由替换子路由

javascript - JSON 中未定义获取选项和选择

angular - 将数据绑定(bind)到 Angular 2 路由组件

npm - 如何从 3000 更改服务器端口?

javascript - Angular 与 CanvasJS 图表在 ngAfterViewInit 中启动

angular - MSAL/B2C 错误 : 'Secure Connection Failed' AFTER getting valid ID token

javascript - 流畅刷新页面

javascript - 在 Angular 模板中循环遍历 Javascript 对象和子对象