This page looks best with JavaScript enabled

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

 ·  ☕ 2 min read  ·  ✍️ Adesh

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.

1
2
3
4
5
<form [formGroup]="testForm">
<label>First Name: <input type="text" formControlName="firstname"></label>
<label>Last Name: <input type="text" formControlName="lastname"></label>
<label>Email: <input type="text" formControlName="email"></label>
</form>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
export class AppComponent implements OnInit {
  
  testForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.testForm = this.formBuilder.group({
      firstname: '',
      lastname: '',
      email: ''
    });

    this.onValueChanges();
  }

  onValueChanges(): void {
    this.testForm.valueChanges.subscribe(val=>{
      console.log(val);
    })
  }
}

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.

1
2
3
4
5
onValueChanges(): void {
    this.testForm.get('firstname').valueChanges.subscribe(val=>{
      console.log(val);
    });
  }

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

Stop Using ElementRef! For DOM Manipulation In Angular

Angular Material Table With Paging, Sorting And Filtering

ng-template, ng-container And ngTemplateOutlet In Angular

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect