Angular2: Subscribe valuechanges in formbuilder
Solution 1
I don't know Ionic but I guess ionViewDidLoad()
is called after ngOnInit()
. Just move the code from ionViewDidLoad()
to the constructor or to ngOnInit()
before the current code.
You should be able to get the price control using
this.purchaseDataForm.get('price').valueChanges.subscribe(value => {
Solution 2
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);
});
}
![SoldierCorp](https://i.stack.imgur.com/EC7Qo.png?s=256&g=1)
SoldierCorp
Full-stack web and mobile developer Portfolio: https://edgardorl.com Youtube: http://youtube.com/SoldierCorp0
Updated on June 16, 2022Comments
-
SoldierCorp about 2 years
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!
-
SoldierCorp over 7 yearsMoving the code to the constructor keeps the error but if I move the valuechanges code to the ionViewDidEnter() the error it's a bit different
ionViewDidEnter error: Cannot read property 'valueChanges' of undefined
but my function to detect the valuechanges is ok? -
Günter Zöchbauer over 7 yearsUh, I missed the
price
. Trythis.purchaseDataForm.get('price').valueChanges.subscribe(value => {
-
SoldierCorp over 7 yearsThe right instruction is
this.purchaseDataForm.controls['price'].valueChanges.subscribe(value => {
please update your answer so I can accept it, thanks! -
Günter Zöchbauer over 7 yearsDid you try
get()
?. AFAIK it's the preferred way. It also allows you to get nested controls with.get('somegroup.subgroup.price')
-
SoldierCorp over 7 yearsYes I tried and I got this
this.purchaseDataForm.controls.get is not a function
-
Günter Zöchbauer over 7 yearsAnd without
controls
? I looked it up in the docs and from what I understand it should work withoutcontrols
. Didn't remember exactly. -
SoldierCorp over 7 yearsYou right, it also works without
controls
, thanks! By the way, I have one more question about the formbuilder and how to disable and input, should I create a new question or you can help through the chat? -
SoldierCorp over 7 years