Skip to content

Instantly share code, notes, and snippets.

@sasxa
Last active May 23, 2017 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sasxa/c2618f7f566d42751b43 to your computer and use it in GitHub Desktop.
Save sasxa/c2618f7f566d42751b43 to your computer and use it in GitHub Desktop.
Angular2 Forms with @ngrx/store
export class _BaseForm {
_builder: FormBuilder;
_group: ControlGroup;
public controls = (value: any = {}) => ({
});
public selector: string = "examples";
public store: Store<any>;
constructor() { }
init(value?: number, key: string = "id") {
this.store.select(state => state.models[this.selector])
.flatMap((items: any, i) => items)
.filter((item: any) => {
return (value !== undefined && item.hasOwnProperty(key)) ? item[key] === value : true;
})
.subscribe(value => {
this.store.dispatch({ type: "ACTIVATE_FORM", payload: value });
});
this.store.select(state => state.forms.active).first()
.subscribe(value => {
this._group = this._builder.group(this.controls(value));
let payload = {};
payload[this.selector] = value;
this.store.dispatch({ type: "UPDATE_FORM", payload });
});
}
reset() {
let values = this.store.value.forms.active;
this._group = this._builder.group(this.controls(values));
}
ngOnDestroy() {
this.store.dispatch({ type: "ACTIVATE_FORM", payload: {} });
}
}
export class ProjectForm extends _BaseForm {
_builder: FormBuilder;
_group: ControlGroup;
public controls = (value: any = {}) => ({
'id': [value.id],
'name': [value.name, Validators.required]
});
public selector: string = "projects";
constructor(
public store: Store<any>,
formBuilder: FormBuilder,
) {
super();
this._builder = formBuilder;
this.init();
}
get projectsForm() { return this._group; }
submit() { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment