Data binding not updating when properties change in Angular2

I cannot figure out how to associate fields with a component so that the fields are updated when properties change in OnDataUpdate ().

The OtherValue field has two-way binding to the input field, and the Name field displays a test when the component is displayed. But when I update the data, none of the fields are updated to display the updated data.

The first registered value of "this.name" is undefined (???), the second is correct, but the field associated with the same property is not updated.

How can a component provide an initial value for a name field, but when the data is updated, the name property is unexpectedly undefined?

stuff.component.ts

@Component({ moduleId: __moduleName, selector: 'stuff', templateUrl: 'stuff.component.html' }) export class BuildingInfoComponent { Name: string = "test"; OtherValue: string; constructor(private dataservice: DataSeriesService) { dataservice.subscribe(this.OnDataUpdate); } OnDataUpdate(data: any) { console.log(this.Name); this.Name = data.name; this.OtherValue = data.otherValue; console.log(this.Name); } 

stuff.component.html

 <table> <tr> <th>Name</th> <td>{{Name}}</td> </tr> <tr> <th>Other</th> <td>{{OtherValue}}</td> </tr> </table> <input [(ngModel)]="OtherValue" /> 
+7
html angular typescript
source share
3 answers

This context is lost if you pass it as in the subscribe() function. You can fix this in several ways:

using bind

 constructor(private dataservice: DataSeriesService) { dataservice.subscribe(this.OnDataUpdate.bind(this)); } 

using an anonymous function wrapper

 constructor(private dataservice: DataSeriesService) { dataservice.subscribe((data : any) => { this.OnDataUpdate(data); }); } 

change function declaration

 OnDataUpdate = (data: any) : void => { console.log(this.Name); this.Name = data.name; this.OtherValue = data.otherValue; console.log(this.Name); } 
+7
source share

The transfer method method thus breaks the this link

 dataservice.subscribe(this.OnDataUpdate); 

use this instead:

 dataservice.subscribe((value) => this.OnDataUpdate(value)); 

Using ()=> (arrow function) this saved and continues to reference the current instance of the class.

+2
source share

You lose this context to save a context that you can use bind .

 dataservice.subscribe(this.OnDataUpdate.bind(this)); 
0
source share

All Articles