【问题标题】:How to detect the changes from the reactive form input using valuechanges in angular 8如何使用角度 8 中的 valuechanges 检测反应形式输入的变化
【发布时间】:2019-07-18 18:57:54
【问题描述】:

我想检测在反应形式中对数量字段所做的更改,因为我正在使用 valuechanges 来检测更改。

我尝试了 valuechanges,但它显示错误为无法读取未定义的属性“valueChanges”

ngOnInit() {


    this.cartItems = this.productService.getCalculateProducts();
    this.cartItems = this.productService._cartItem;

    this.initForm();
    this.cartFormChanges();


  console.log(this.cartForm.controls['items']);

  }

  initForm() {
    this.cartForm = this.fb.group({
      items: this.fb.array([])
    })

    this.cartItems.forEach(item => {
      (this.cartForm.get('items') as FormArray).push(this.createFormItem(item));
    });



  }
  createFormItem(product: Product): FormGroup {
    return this.fb.group({
      id: product.id,
      qty: [product.productQty, [Validators.max(product.productQty), Validators.min(1)]],
      price: product.productPrice
    });
  }

  get items() {
    return this.cartForm.controls.items as FormArray;
  }
  cartFormChanges() {
    this.cartForm.controls["qty"].valueChanges.subscribe((changes) => {
      console.log('Object', changes);
      console.log('qty', this.cartForm.value.qty);

    });

  }

只要数量字段值在反应形式中发生变化,就应该检测到该值。

【问题讨论】:

  • "qty" 不是 cartForm 的控件,而是作为 "items" 数组一部分的组的控件。这就是您收到“未定义错误”的原因。

标签: angular


【解决方案1】:

您必须从购物车表单中获取项目数组。然后遍历每个项目并订阅值更改。

const control = <FormArray>this.cartForm.controls['items'];

for (i = 0; i < control.length; i++) {
      control.controls[i].get("qty").valueChanges.subscribe(x => {
        console.log(x) 
      })
}

【讨论】:

  • 我已编辑。再次检查我错过了控件属性。
猜你喜欢
  • 1970-01-01
  • 2019-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-21
  • 2021-06-04
  • 1970-01-01
相关资源
最近更新 更多