Kristoffer Berge Kristoffer Berge - 6 months ago 37
HTML Question

Data binding not updating when property changes in Angular2

I can't figure out how to bind the fields to the component so that the fields update when i change the properties in OnDataUpdate().

The field "OtherValue" has a working two way binding to the input-field and the field for "Name" displayes "test" when the component is displayed. But when i refresh the data, none of the fields are updated to display the updated data.

The first logged value of "this.name" is undefined(???), the second is correct, but the field bound to the same property does not update.

How can the component provide the initial value for the name-field, but when the data update is trigged, the name-property is suddenly 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" />

Answer

I believe the this context is lost if you pass it like that in the subscribe() function. You can fix this in several ways:

by using bind

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

by using an anonymous arrow function wrapper

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

change the declaration of the function

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