【发布时间】: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