将模板驱动的变量分配给活动表单

时间:2018-02-13 07:44:25

标签: angular angular-reactive-forms angular4-forms

如何将ngOnInit()中的this.product.amount分配给名为available_amount的反应式表单变量?有办法吗?谢谢。

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

1 个答案:

答案 0 :(得分:0)

创建一个函数来创建表单

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

然后,在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");
                })
        }); 
} 

注意:我支持你的this.product根据你的真实代码有一个名为“金额”的属性