Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular FormControl valueChanges doesn't work

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));
  }
}
like image 412
M.J Avatar asked Jun 17 '17 08:06

M.J


People also ask

What is the use of ValueChanges method on a FormControl?

The ValueChanges is an event raised by the Angular forms whenever the value of the FormControl, FormGroup or FormArray changes. It returns an observable so that you can subscribe to it. The observable gets the latest value of the control. It allows us to track changes made to the value in real-time and respond to it.


2 Answers

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

ngOnInit() {  
   this.frm1.get('family').valueChanges.subscribe( x => console.log(x));
}
like image 149
Amit Chigadani Avatar answered Oct 17 '22 06:10

Amit Chigadani


Try this:

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

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

export class AppComponent implements AfterViewInit, OnInit{ 

frm1 : FormGroup;

constructor( private formBuilder: FormBuilder){}

ngOnInit(): void {
    this.formInit();
    this.formSet();
}

formInit(): void {
    this.frm1 = this.formBuilder.group({
        name: [''],
        family['']
    })
}

formSet(): void {
    const editForm = {
        name: 'test-name',
        family: 'test familty',
    };
    this.frm1.patchValue(editForm) 
}

ngAfterViewInit(){  
this.frm1 .controls.family.valueChanges.subscribe(
       () => {
              console.log(this.frm1 .controls.family.value)
             }
        )
      }
}
like image 35
Ketan Akbari Avatar answered Oct 17 '22 06:10

Ketan Akbari