【问题标题】:Angular NGRX/Observables and Reactive FormsAngular NGRX/Observables 和响应式表单
【发布时间】:2018-05-05 10:56:31
【问题描述】:

目前我有一个项目使用 NGRX 作为其存储和反应形式。

在我的应用程序中,我想将我状态中的活动项映射到反应形式。所以在我的组件中,我有类似的东西:

export class MyComponent {

    active$: Observable<any>;

    form = this.fb.group({
        name: ['', [Validators.required]],
        description: ['', Validators.maxLength(256)]
    });

    constructor(private fb: FormBuilder, private store: Store<any>) {
        this.active$ = store.select(store => store.items);
    }
    
}

为了避免订阅商店并选择我的商品,我创建了一个指令来将我的 observable 绑定到我的表单:

import { Directive, Input } from '@angular/core';
import { FormGroupDirective } from '@angular/forms';

@Directive({
    selector: '[connectForm]'
})
export class ConnectFormDirective {

    @Input('connectForm')
    set data(val: any) {
        if (val) {
            this.formGroupDirective.form.patchValue(val);
            this.formGroupDirective.form.markAsPristine();
        }
    }

    constructor(private formGroupDirective: FormGroupDirective) { }

}

现在在我的表单中,我只是像这样绑定它:

<form [formGroup]="form" novalidate (ngSubmit)="onSubmit()" [connectForm]="active$ | async">
</form>

我的问题是:

  • 这是个好主意/有没有更好的方法来处理这个问题?

我想,对于复杂的场景,你最终将不得不订阅组件中的 observable。

【问题讨论】:

    标签: angular rxjs ngrx angular-reactive-forms


    【解决方案1】:

    您应该考虑将组件拆分为“连接”和“演示”组件。您的连接组件将负责查询商店并向商店发出操作,您的表示组件将在其中创建一个表单组并接受来自商店的值作为@Input 参数。然后,您可以在表示组件中侦听表单组中的值更改,并向连接的组件引发具有更新值的事件。然后,连接的组件将处理来自表示组件的事件并引发一个新的操作来更新存储中的值。

    【讨论】:

      【解决方案2】:

      不,这对我来说似乎是一种不好的做法。表单应该是在父视图组件中使用的自己的组件。然后,如果它应该用于编辑,则可以使用 @Input 装饰器传递数据。

      所以在你的父组件中你会做这样的事情:

      <form-component [data]="active$ | async"></form-component>
      

      在表单组件中你可以这样做:

      ngOnInit{
          if(this.data)
              this.form.patchValue(this.data)
      }
      

      要使用 ReactiveForms 禁用表单控件,请使用 disable 方法。

      【讨论】:

        猜你喜欢
        • 2020-05-19
        • 2020-05-02
        • 1970-01-01
        • 1970-01-01
        • 2018-07-14
        • 2018-06-22
        • 1970-01-01
        • 1970-01-01
        • 2018-12-20
        相关资源
        最近更新 更多