如何处理单向数据流中的 Angular 2 表单?尤其是在多个父/子组件之间进行验证?
我正在使用 ngrx/store 和模型驱动的表单以及表单构建器。是否有可能在 React 中做类似表单缩减器的事情并将其作为 Store 的一部分?
你有关于它的一些文章吗?
最佳答案
我创建了一个名为 ngrx-forms 的库那正是你想要的。您可以通过以下方式在 npm 上获取它:
npm install ngrx-forms --save
我建议查看 github 页面上的完整自述文件,但您可以在下面找到一些示例,说明在安装后启动和运行该库需要执行的操作。
导入模块:
import { StoreModule } from '@ngrx/store';
import { NgrxFormsModule } from 'ngrx-forms';
import { reducers } from './reducer';
@NgModule({
declarations: [
AppComponent,
],
imports: [
NgrxFormsModule,
StoreModule.forRoot(reducers),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
通过 createFormGroupState
在状态树的某处添加一个组状态,并在你的 reducer 中调用 formGroupReducer
:
import { Action } from '@ngrx/store';
import { FormGroupState, createFormGroupState, formGroupReducer } from 'ngrx-forms';
export interface MyFormValue {
someTextInput: string;
someCheckbox: boolean;
nested: {
someNumber: number;
};
}
const FORM_ID = 'some globally unique string';
const initialFormState = createFormGroupState<MyFormValue>(FORM_ID, {
someTextInput: '',
someCheckbox: false,
nested: {
someNumber: 0,
},
});
export interface AppState {
someOtherField: string;
myForm: FormGroupState<MyFormValue>;
}
const initialState: AppState = {
someOtherField: '',
myForm: initialFormState,
};
export function appReducer(state = initialState, action: Action): AppState {
const myForm = formGroupReducer(state.myForm, action);
if (myForm !== state.myForm) {
state = { ...state, myForm };
}
switch (action.type) {
case 'some action type':
// modify state
return state;
default: {
return state;
}
}
}
在组件中公开表单状态:
import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { FormGroupState } from 'ngrx-forms';
import { Observable } from 'rxjs/Observable';
import { MyFormValue } from './reducer';
@Component({
selector: 'my-component',
templateUrl: './my-component.html',
})
export class MyComponent {
formState$: Observable<FormGroupState<MyFormValue>>;
constructor(private store: Store<AppState>) {
this.formState$ = store.select(s => s.myForm);
}
}
在模板中设置控件状态:
<form novalidate [ngrxFormState]="(formState$ | async)">
<input type="text"
[ngrxFormControlState]="(formState$ | async).controls.someTextInput">
<input type="checkbox"
[ngrxFormControlState]="(formState$ | async).controls.someCheckbox">
<input type="number"
[ngrxFormControlState]="(formState$ | async).controls.nested.controls.someNumber">
</form>
关于forms - Angular 2 + ngrx(redux) + 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38668337/