Bhimisetty
Bhimisetty

Reputation: 236

FormControl ValueChanges event not firing when setValue is called

I have the following code for an Angular 4 type-ahead component: There is a FormControl in the FormGroup which is tied with the html and it works perfectly.

this.ProfileForm.controls["code"]

The valueChanges event is firing when i change in the textbox. Now when i update the formcontrol value through programatically the valueChanges event is not firing. The following is the lines of code i written.

this.ProfileForm.controls["code"].setValue("someValue");

this.ProfileForm.controls["code"].valueChanges.subscribe(() => {
            console.log("modified");}, () => { console.log("error") }, () => { console.log("completed") });

Any suggestion is appreciated.

Upvotes: 14

Views: 32770

Answers (2)

Amir Aghajani
Amir Aghajani

Reputation: 387

It may be helpful. I have similar problem because of incorrect value set.

this.formGroup = this._formBuilder.group({
  city: [new Location()]
});

this.cityControl = this.formGroup.get('city');

this.citiesListOptions = this.cityControl.valueChanges.pipe(
  map(name => this._filterCity(name))
);

when i used this:

this.cityControl.patchValue(null); 

then cityControl.valueChanges not fire again.

when i correct to this, worked:

this.cityControl.patchValue(new Location() ) 

Upvotes: 0

Vova Bilyachat
Vova Bilyachat

Reputation: 19514

Change it to subscribe first and then setValue

this.ProfileForm.controls["code"].valueChanges.subscribe(() => {
            console.log("modified");}, () => { console.log("error") }, () => { console.log("completed") });

this.ProfileForm.controls["code"].setValue("someValue");

Because in your code you are changing value while you are not yet subscribed.

Upvotes: 15

Related Questions