首页 > 解决方案 > 订阅时未更新角度模型字段

问题描述

简化后我得到了一个观点:

<table class="table table-bordered table-striped">
<tr>
  <td>
    <label>First Name</label>
    <input type="text" class="form-control" [(ngModel)]="profile.FirstName">
  </td>
  <td>
    <label>Last Name</label>
    <input type="text" class="form-control" [(ngModel)]="profile.LastName">
  </td>
 </tr>
</table>

构造函数创建空白配置文件并且 ngOnInit 检查更改的组件:

profile: Profile;
sub: any;
constructor(private serv: ProfileService, private route: ActivatedRoute) {
  this.profile = new Profile('', '');
}

ngOnInit(): void {
  this.sub = this.route.params.subscribe(params => {
    const id = params['id'];
    this.serv.getProfile(id).subscribe(res => {
      console.log(res);
      this.profile = res;
      // this.profile.LastName = res.LastName; doesn't work either
    });
  });
}

在控制台上记录了正确的配置文件,但未更新表字段。怎么了?谢谢你的帮助!

标签: angular

解决方案


为了触发其绑定,Angular 正在寻找的是参考更改。

当您像这样分配时,您不会更改参考:

this.profile.LastName = res.LastName;

你想做的是像这样使用传播运算符:

this.profile = { ...this.profile, lastName: res.lastName }

推荐阅读