36

I would like to detect the value of change event to the input on form.component.ts. I would not like to call the function ex: (onChange) = "function($event.target.value)"

public form: FormGroup;

constructor(private formBuilder: FormBuilder){ 

}

private loadForm(){
    this.form = this.formBuilder.group({
        tipo: [null, Validators.required],
        nomeRazao: [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(64)])],
        apelidoFantasia: [null, Validators.compose([Validators.required, Validators.minLength(3), Validators.maxLength(64)])],
        cpfCnpj: [null, Validators.compose([Validators.required, Validators.minLength(11), Validators.maxLength(14)])],
        rgIe: [null],
        contato: this.formBuilder.group({
            email: [null],
            telefone: [null]
        }),
        endereco: this.formBuilder.group({
            cep: [null, Validators.pattern('^([0-9]){5}([-])([0-9]){4}$')],
            uf: [null],
            cidade: [null],
            bairro: [null, Validators.required],
            logradouro: [null],
            complemento: [null],
            numero: [null, Validators.pattern('/^\d+$/')]
        })
    });
}

ngOnInit() {
    this.loadForm();
}

3 Answers 3

49

You can subscribe to your form changes by using this :

this.form.valueChanges.subscribe(() => {
   if (this.registerForm.controls['yourControlName'].value === 'someValue') {
      // 
   }
 });
1
  • 5
    good answer, but better type-safe would be: this.form.valueChanges.subscribe((data) => { if (data.yourControlName === 'someValue') { // } }); Commented Aug 1, 2017 at 14:57
48

For detecting changes in value of a particular field, 'valueChanges' event on that field can be subscribed, as shown below:

this.myForm.get('formcontrolname').valueChanges.subscribe(val => {
    this.message = val;
  });
3
  • 1
    Can you please tell a little bit more, Where to include this snippet? Actually I have to detect the change of checkbox of dynamic form. Commented Dec 11, 2019 at 9:48
  • 1
    @SaurabhSinghRajput put it in ngOnInit() Commented Feb 10, 2020 at 6:19
  • Here is a good link on the subject, but as Tom Stickel mentions put it inside ngOnInit instead of ngOnChanges: alligator.io/angular/reactive-forms-valuechanges Commented May 12, 2020 at 16:29
0

For people who are checking for higher versions of Angular or to whom the accepted solution isn't working,

Try this

this.myForm.valueChanges.subscribe(val => {
this.message = val.formcontrolname;});

the approach is to use the variables inside the change detection and you can restrict it with the respective form control name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.