我不知道如何将字段绑定到组件,以便在我更改 OnDataUpdate() 中的属性时更新字段。
字段“OtherValue”具有绑定到输入字段的两种工作方式,“名称”字段在显示组件时显示“测试”。但是当我刷新数据时,没有任何字段被更新以显示更新后的数据。
“this.name”的第一个记录值是未定义的(???),第二个是正确的,但绑定到同一属性的字段不会更新。
怎么组件给name-field提供初始值,触发数据更新时,name-property突然undefined?
东西.component.ts
@Component({
moduleId: __moduleName,
selector: 'stuff',
templateUrl: 'stuff.component.html'
})
export class StuffComponent {
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);
}
东西.component.html
<table>
<tr>
<th>Name</th>
<td>{{Name}}</td>
</tr>
<tr>
<th>Other</th>
<td>{{OtherValue}}</td>
</tr>
</table>
<input [(ngModel)]="OtherValue" />
原文由 Kristoffer Berge 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您像在
subscribe()
函数中那样传递它,那么this
上下文将丢失。您可以通过多种方式解决此问题:通过使用绑定
通过使用匿名箭头函数包装器
更改函数的声明