Proper integration of forms in Angular 8+ applications using ngxs
npm install ngxs-forms@ngrx/store, this fork is updated to be used with @ngxs/store store.
bash
npm install ngxs-forms --save
or if you are using yarn
yarn add ngxs-forms
`
This library has a peer dependency on @angular/core, @angular/common, @angular/forms, and @ngxs/store, so make sure appropriate versions of those packages are installed.
#### Quick start
Add NgxsFormsModule.forRoot() to root app module
`typescript
import { NgxsFormsModule } from 'ngxs-forms';
// ...
@NgModule({
declarations: [
AppComponent
],
imports: [
// ...
NgxsFormsModule.forRoot()
],
// ...
bootstrap: [AppComponent]
})
export class AppModule { }
`
Define NGXS state
`typescript
import { FormGroupState, createFormGroupState } from 'ngxs-forms';
// ...
interface FormModel {
id: number;
name: string;
// ...
}
interface StateModel {
loading: boolean;
specialForm: FormGroupState;
//...
}
const initialModelState: FormModel = {
id: null,
name: '',
// ...
}
const SOME_FORM_ID = '[Some scope] Special form';
const initialSpecialFormState = createFormGroupState(SOME_FORM_ID, initialModelState);
const initialState: StateModel = {
loading: false,
specialForm: initialSpecialFormState
};
@State({
name: 'someSpecialState',
defaults: initialState
})
@Injectable()
export class SpecialState {
// ...
}
`
Add NgxsFormsModule in feature module and use state in component (no special reducers needed)
`typescript
// ...
@NgModule({
declarations: [
SomeComponent
],
imports: [
// ...
NgxsFormsModule
],
})
export class SomeFeatureModule { }
// ...
@Component({
selector: 'app-special',
template:
,
})
export class SomeComponent implements OnInit {
@Select(SpecialState) specialState$: Observable;
``