Angular FormControl valueChanges doesn't work

M.J picture M.J · Jun 17, 2017 · Viewed 42.9k times · Source

I want to get one of my forms ("family") value if changed by subscribing but it seems something is wrong because I got nothing on my console's log.

import { Component , AfterViewInit } from '@angular/core';
import {FormGroup,FormBuilder} from '@angular/forms';
import {Observable} from 'rxjs/Rx';

@Component({
  selector: 'app-root',
  template: `<form [formGroup]="frm1">
<input type="text" formControlName="name" >
<input type="text" formControlName="family">
</form>
`,

})

export class AppComponent implements AfterViewInit{
  frm1 : FormGroup;

  constructor( fb:FormBuilder){
    this.frm1 = fb.group({
      name : [],
      family: []
    });
  }
  ngAfterViewInit(){
    var search = this.frm1.controls.family;
    search.valueChanges.subscribe( x => console.log(x));
  }
}

Answer

Amit Chigadani picture Amit Chigadani · Jun 17, 2017

Use get method on form variable frm1. And use ngOnInit() instead of ngAfterViewInit()

ngOnInit() {  
   this.frm1.get('family').valueChanges.subscribe( x => console.log(x));
}