-
-
Save talamaska/eca2e1e839477a7212394e10c93b66ae to your computer and use it in GitHub Desktop.
Angular2 Forms with @ngrx/store
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: {} }); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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