Search code examples
typescriptangular-template-form

Angular NgForm.setValue({}) with optional fields


I have a Template driven form in angular, on which i want to populate valuees when i click on a product. The fields 'description' and 'imageUrl' might be undefined which break my form if i don't take care of it. I managed to do it with this solution :

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

Is there a simpler or cleaner way to do that ? Thanks !


Solution

  • Angular has patchValue and setValue

    While setValue expects every field defined in the form to be supplied, patchValuedoes not.

    so in your example

    // 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,
        });
    

    this is valid for patchValue but not setValue -> use patchValue for your case

    Notice that the form itself holds a formGroup called form you have to use because ngForm doesn't have the patchValue method.

    UPDATE
    There are some caveats using pachValue with template driven forms depending on when you call patchValue.
    You could also use somekind of mapper/initializer where you set every missing or undefined member of your object.
    Personally I would go with the patchValue route if possible.