14

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.

7
  • 1
    Are you sure that you are not reinitialise form? Commented Aug 30, 2017 at 12:44
  • Yes, i am not reinitialising. Commented Aug 30, 2017 at 12:44
  • can you please post full sourcecode? not just parts from different places Commented Aug 30, 2017 at 12:45
  • Btw in code you have setValue before subscribe? Commented Aug 30, 2017 at 12:48
  • Yes, it is positioned correctly in the code. Commented Aug 30, 2017 at 12:53

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

4 Comments

As in the comment, the position of codes are correct position as you mentioned.
@Bhimisetty what do you mean?
My code is like this only this.ProfileForm.controls["code"].valueChanges.subscribe(() => { console.log("modified");}, () => { console.log("error") }, () => { console.log("completed") }); this.ProfileForm.controls["code"].setValue("someValue");
#"¤%/%#"§"! me! It's an hot observable!? Well, thanks for the help - was getting frustrated why it didn't work when it should :D
0

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() ) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.