Angular NgForm.setValue({}) 带有可选字段

Angular NgForm.setValue({}) with optional fields

我在 angular 中有一个模板驱动的表单, 当我点击一个产品时,我想在上面填充值。 字段 'description' 和 'imageUrl' 可能未定义,如果我不处理它会破坏我的表单。 我设法用这个解决方案做到了:

  private initFormEdit() {
    this.product = this.productService.fetchProduct(this.restaurantId, this.productId);

    // I'm using a ternaty operator to put a default value if objects are empty
    const description = this.product.description ? this.product.description : '';
    const imageUrl = this.product.imageUrl ? this.product.imageUrl : '';

    this.productForm.setValue({
      name: this.product.name,
      category: this.product.category,
      description,
      price: this.product.price,
      imageUrl
    });
  }

有没有更简单或更简洁的方法来做到这一点? 谢谢!

Angular 有 patchValuesetValue

虽然 setValue 期望提供表单中定义的每个字段,但 patchValue 没有。

所以在你的例子中

// this throws
this.productForm.form.setValue({
      name: this.product.name,
      category: this.product.category,
      price: this.product.price,
    });

//this does not throw
this.productForm.form.patchValue({
      name: this.product.name,
      category: this.product.category,
      price: this.product.price,
    });

这对 patchValue 有效,但对 setValue 无效 -> 针对您的情况使用 patchValue

请注意,表单本身包含一个名为 formformGroup,您必须使用它,因为 ngForm 没有 patchValue 方法。

更新
根据您调用 patchValue.
的时间,有 使用带有模板驱动表单的 pachValue 您还可以使用某种 mapper/initializer 来设置对象的每个缺失或未定义的成员。
如果可能的话,我个人会选择 patchValue 路线。