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') {
      // 
   }
 });
Sign up to request clarification or add additional context in comments.

1 Comment

good answer, but better type-safe would be: this.form.valueChanges.subscribe((data) => { if (data.yourControlName === 'someValue') { // } });
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 Comments

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.
@SaurabhSinghRajput put it in ngOnInit()
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
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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.