Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subscribe to valueChanges from input FormControl in FormGroup

Tags:

angular

In Angular 4, I'm trying to subscribe to the valueChanges of a FormControl. Neither of the versions below is working. I'm not seeing any errors. The form.value JSON is updating as I type, but the subscription isn't working.

myForm: FormGroup; public firstName = new FormControl(); public lastName = new FormControl();  this.myForm = this.formBuilder.group({        firstName: '',       lastName: '', });  this.myForm.controls.firstName.valueChanges.subscribe(value => {       console.log(value); });   this.myForm.get('firstName').valueChanges.subscribe(value => {       console.log('name has changed:', value) }); 

Here's a template snippet.

<form #myForm="ngForm">  <md-input-container>     <input mdInput name="firstName" [(ngModel)]="firstName" placeholder="enter name"/> </md-input-container> 
{{ myForm.value | json }}
like image 602
beachCode Avatar asked Jul 19 '17 01:07

beachCode


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.

How do I get data from FormControl?

Get and Set Value To fetch the value of a form control, we have to use value property on the instance of FormControl in our class. In the same way we can fetch the value in HTML template.


1 Answers

I think you are missing some thing here with formGroup and formControlName you should do:

myForm: FormGroup; firstName = ''; lastName = ''; 

on ngOnInit

this.myForm = this.formBuilder.group({     firstName: [this.firstName],     lastName: [this.lastName] });  this.myForm.controls['firstName'].valueChanges.subscribe(value => {   console.log(value); }); 

and In HTML

<form [formGroup]="myForm">    ...    <input name="firstName" [(ngModel)]="firstName" formControlName="firstName" placeholder="enter name"/>     <input name="lastName" [(ngModel)]="lastName" formControlName="lastName" placeholder="enter last name"/>     ... </form> 
like image 190
Touqeer Shafi Avatar answered Oct 06 '22 05:10

Touqeer Shafi