【问题标题】:Angular 11: How to get updates to Reactive Form from a service shared by multiple componentsAngular 11:如何从多个组件共享的服务中获取对 Reactive Form 的更新
【发布时间】:2021-08-02 13:51:48
【问题描述】:

在 Angular 11 中, 使用 Reactive Forms 从共享服务中的属性获取更新的最佳方法是什么?

如果一个组件更新服务中的值,另一个组件应该如何在不将所有内容更改为主题然后修补现有表单的情况下获得更改?

我定义形式:

<form [formGroup]="form" class="form-horizontal" role="form">
<div formGroupName="user">
    <mat-form-field>
        <input matInput formControlName="name" placeholder="Username">
    </mat-form-field>
    <mat-form-field>
        <input matInput formControlName="fullName" placeholder="Full Name">
    </mat-form-field>
</div>
createForm() {
this.form = this.fb.group({
  user: this.fb.group({
    name: [this.userService.currentUser.name],
    fullName: [this.userService.currentUser.fullName]
  }),
});

}

这只是一个示例,但是如果 userService.fullName 中的值发生更改,我将如何更新此组件的表单?我可以使用 Subject,但我必须始终设置 currentUser 并且不能只更新子属性,在更复杂的对象中,事情似乎变得更加混乱。

我可以为此使用模板驱动的表单,但是验证会更加复杂。有没有更好的方法来做到这一点?

类似于this question,但我还没有真正看到好的答案。

【问题讨论】:

  • form.valuesChanges 还不够吗?

标签: angular angular-reactive-forms angular-forms


【解决方案1】:

为 FormGroup(或任何 Form 元素)提供服务:patchValue 或 setValue(部分或全部更新)

FormGroup(或任何 Form 元素)到 Service : valueChanges

// FormGroup to service (don't forget to unsubscribe)
this.myFormGroup.valueChanges.subscribe(data => this.service.updateData(data));

// Service to FormGroup (don't forget to unsubscribe)
this.service.data$.subscribe(data => this.myFormGroup.patchValue(data));

【讨论】:

  • 这不是从当前组件中获取数据并专门保存它。如果两个组件都使用来自同一服务的数据。当我从组件 1 保存它,然后组件 2 的表单已经被初始化,所以当组件 1 保存它的数据时它不会更新,我该怎么办。我是否应该使用服务数据触发对所有组件的表单更新?
  • 据我了解:您有 2 个组件(表单)在其 FormGroup 中使用相同的数据。当其中一个正在保存数据时,您想要更新所有组件(覆盖),对吗?您应该使用 Observable 将您的数据存储在您的服务中,并在您从该 Observable 接收到新数据时更新您的 FormGroups。
猜你喜欢
  • 2018-03-10
  • 2017-02-21
  • 2020-09-27
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-20
  • 2019-06-15
相关资源
最近更新 更多