Angular2: Subscribe valuechanges in formbuilder

SoldierCorp picture SoldierCorp · Nov 24, 2016 · Viewed 14k times · Source

I'm using ionic2 with angular2 and I have a form built with formbuilder but I want to detect new changes of a certain input.

ionViewDidLoad() {
  this.purchaseDataForm = this.formBuilder.group({
    kms: ['', Validators.required],
    lts: ['', Validators.required],
    price: ['', Validators.required],
    total: ['', Validators.required]
  });
}

So that's how my form is validated but I want to subscribe the valuechanges of the price and the lts inputs, do you know how to do that?

I'm trying with the following function but it displays Cannot read property 'valueChanges' of undefined

 ngOnInit() {
  this.purchaseDataForm.price.valueChanges.subscribe(value => {
    console.log(value);
  });
}

Thanks!

Answer

lastWhisper picture lastWhisper · Nov 24, 2016

The price is not a direct attribute of your form. The price is located in the "controls"-object of your form. So your code should look like this:

ngOnInit() {
    this.purchaseDataForm.controls.price.valueChanges.subscribe(value => {
        console.log(value);
    });
}