将模板驱动变量分配给反应形式

Assign Template Driven Variable To Reactive Form

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

创建一个函数来创建表单

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 有一个 属性 叫做 "amount" 根据你的真实代码更改