Search code examples
angularangular-reactive-formsangular4-forms

Assign Template Driven Variable To Reactive Form


How can i assign the this.product.amount from the ngOnInit() to my reactive form variable called available_amount? Is there a way to do it? Thank you.

this.productForm = this.fb.group({
            available_amount: [null, Validators.required]
        })


ngOnInit() {
        this.subscription = this.route.params
        .subscribe((params: Params) => {
            this.id = +params['id'];
            this.ProductsService.getProduct(this.id)
            .subscribe(
                (data:any) => {
                    this.product = data.product[0];
                    console.log(data);
                },
                error => {
                    console.log(error);
                    alert("ERROR");
                })
        }); 
} 

Solution

  • make a function to create the form

    createForm(data:any)
    {
      this.productForm = this.fb.group({
          <!--if pass data to argument, the value of available_amout was
              data.amount, else null -->
              available_amount: [data?data.amount:null, Validators.required]
      })
    }
    

    Then, use this function in ngOnInit

    ngOnInit() {
            this.subscription = this.route.params
            .subscribe((params: Params) => {
                this.id = +params['id'];
                this.ProductsService.getProduct(this.id)
                .subscribe(
                    (data:any) => {
                        this.product = data.product[0];
                        createForm(this.product) //<--call the function
                    },
                    error => {
                        console.log(error);
                        alert("ERROR");
                    })
            }); 
    } 
    

    NOTE: I supouse your this.product has a property called "amount" change according your real code