Search code examples
angularangular2-services

Unexpected result when updating a bound component value via a service


I am using Angular 4.3.6 and my project is set up using the Angular CLI.

My issue is with a component/service interaction. I have made a plunker that demonstrates it and would love it if anyone can explain what the problem is because I am stumped.

I have a component that features an <input type='text' [value]='labelStr'> where labelStr is a property of that component.
I also have a service that declares a BehaviourSubject. The first component subscribes to this subject.

When you click into the field, enter some new text then click away, the characters that you typed are sent to a service. In this example the service simply receives the input then emits it back out via the subject.

The component received the notification over its subscription and updates the labelStr property to be the received value pre-pended by the string Foo.

Most of the time it works as expected - type in some chars, click out, the value is updated to be Foo [your chars]. The problem arises when you enter text, click out then click back in and enter the same text again. In this case the value does not seem to update and for the life of me I can't see why not. I really hope it is something embarrassingly obvious that I can fix easily.
Please shout if I'm not explaining myself well.

Thanks for any help you can offer.


Solution

  • If you use ngModel instead of value, the issue will be resolved (confirmed locally on plunker) as it forces the 2-way binding automagically. These are the changes I made.

    First import FormsModule to app.ts,

    import {FormsModule} from '@angular/forms'
    
    @NgModule({
      imports: [ BrowserModule, FormsModule ],
      declarations: [ App, InputWidgetComponent],
      bootstrap: [ App ],
    
    })
    export class AppModule {}
    

    In input-widget.ts, change the template for input to,

    <input type="text" [(ngModel)]="labelStr"
        (focus)="handleFocus($event)"
        (blur)="handleBlur($event)">
    

    Hope it helps