【问题标题】:Angular NgForm.setValue({}) with optional fields带有可选字段的 Angular NgForm.setValue({})
【发布时间】:2020-06-11 11:05:10
【问题描述】:

我有一个模板驱动的角度形式, 当我单击产品时,我想在其上填充值。 '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
    });
  }

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

【问题讨论】:

    标签: typescript angular-template-form


    【解决方案1】:

    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 方法。

    更新
    some caveats 使用pachValue 和模板驱动的表单,具体取决于您何时调用patchValue
    您还可以使用某种映射器/初始化器,在其中设置对象的每个缺失或未定义成员。
    如果可能的话,我个人会选择patchValue 路线。

    【讨论】:

    • 感谢您的重播,但实际上 NgForm(模板驱动表单)不存在 patchValue(),如果我没记错的话
    • patchValue 确实存在于模板驱动的表单中。但是有一些警告,如here 所述。另一种方法是创建某种初始化程序,您可以在其中初始化任何丢失/未定义的成员。我更新了我的答案。
    • 哦,我明白了为什么我没有找到patchValue方法,你写的有一个小错误。 PatchValue 不是 NgForm 类的方法,而是 FormGroup 类的方法。所以它只需稍作改动即可工作:this.productForm.control.patchValue({name: this.product.name,category: this.product.category,price: this.product.price,description: this.product.description,imageUrl: this.product.imageUrl}); }); 现在它不再抛出了。非常感谢!
    • 你是对的,我更新了我的答案。如果它对你有帮助,我会很感激你接受它:)
    • 完成!谢谢!
    猜你喜欢
    • 2016-06-14
    • 2012-10-07
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2014-04-12
    • 2017-04-06
    • 2023-04-06
    • 2019-07-24
    相关资源
    最近更新 更多