Set reactive form after data loaded (async) - Angular 5

后端 未结 3 1729
执笔经年
执笔经年 2020-12-19 05:05

I am trying to update the form values after loading values from an API. I tried using the *ngIf technique but the form is not visible even when the form is set.

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-19 05:16

    You can use setValue or patchValue which data async for you FormGroup.

    private initForm(): void {
        // For update product
        if (this.isUpdate) {
          this.productService.getProduct(this.id)
            .subscribe((product: Product) => {
              this.productForm.patchValue({
                name: product.name,
                price: product.price,
                description: product.description,
                image: product.image
              });
            });
        }
        // For create product
        this.productForm = new FormGroup({
          name: new FormControl(null, [
            Validators.required,
            Validators.minLength(8),
            Validators.maxLength(35)
          ]),
          price: new FormControl(null, [
            Validators.required,
            Validators.min(5000),
            Validators.max(50000000),
          ]),
          description: new FormControl(null, [
            Validators.required,
            Validators.minLength(8),
            Validators.maxLength(500)
          ]),
          image: new FormControl(null, Validators.required)
        });
      }
    

提交回复
热议问题