How To Listen Changes In Reactive Form Controls Using valueChanges In Angular
Photo: Dario

How To Listen Changes In Reactive Form Controls Using valueChanges In Angular

In this blog, we are going to learn how to listen to changes in reactive form controls. Most of the time, there are some changes in our form controls, which are created using either FormGroup or FormControl. These reactive form instances like FormGroup and FormControl have a valueChanges method that returns an observable that emits the latest values.

You can subscribe to valueChanges and perform your app logic over there. Let’s take a very simple example of valueChanges in our reactive form. We are going to create three input fields and track their values using valueChanges in reactive form.

Here, you can see, we have created three input fields: firstName, lastname and email using the FormBuilder. After that, we have created a function onValueChanges() and call it in the ngOnInit().

In the onValueChanges(), we are subscribing to our complete form to track changes in any of the input fields and printing them in console log. See the output below:

valueChanges in reactive form.
valueChanges

As you type in any of the input fields, it will emit the changes to our console log.

Instead of listening changes on complete form fields, you can listen for specific form field as well.

Just change our onValueChanges() function, and get the form field firstname and subscribe to the change event. here is the output:

valueChanges in reactive form

As you type in firstName form field, it will emit the changes in the console log.

Summary

In this tutorial, we learned about very basic but important concept of detecting the changes in our form fields.

Further Reading

Adesh

Hi, I am Adesh. I am a senior software engineer having more than 12 years of software development experience. I am a full stack developer and interested in writing the technical post on programming. I am currently working in New York City area.

This Post Has 3 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Close Menu