AlphaBeta
AlphaBeta

Reputation: 1033

Angular service not updating component html element

I have a property in an object in an Angular service that is bound to a text field in a component's html.

When the property is updated by the service, the new value is not showing in the html element until I click on the element.

I cannot figure out why the new value isn't immediately showing in the text field without having to click on the element to get the new value.

The console.log message in the update function shows that the object is updated correctly, it's just that the data is not making it through to the form field until the element is clicked.

The code is below:

parent.component.html

<input [(ngModel)]="service.serviceObj.data" type="text" />

service.service.ts

public serviceObj = {} as any;

...

updateObj() {
    this.serviceObj.data = 'new value';
    console.log('this.serviceObj = ', this.serviceObj);
}

...

Upvotes: 0

Views: 832

Answers (2)

MauricioCavallini
MauricioCavallini

Reputation: 1

you can always make a copy of the object like this:

 const obj= JSON.parse(JSON.stringify(<objToCopy>));

then make the mutation in the obj and assign the service property to the mutated copy obj ("this.yourObj = obj")

Upvotes: 0

Mathew Berg
Mathew Berg

Reputation: 28750

Your input is referencing:

service.selectedMarker.data

But your setting:

this.serviceObj.data = 'new value'

serviceObj vs selectedMarker. Did you mean to do this?

<input [(ngModel)]="service.serviceObj.data" type="text" />

Upvotes: 1

Related Questions