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 }}
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With