Skip to content

Instantly share code, notes, and snippets.

@newmanbrad
Last active September 22, 2016 15:50
Show Gist options
  • Save newmanbrad/2e9129e593afd66251ba51eb4fcb5244 to your computer and use it in GitHub Desktop.
Save newmanbrad/2e9129e593afd66251ba51eb4fcb5244 to your computer and use it in GitHub Desktop.
Example code showing an NG2 component interacting with Redux.
/***
* Actions Example
*
* Here you can see "addClient" method dispatching a change to the
* Reducers in order the record the new state change.
***/
@Injectable()
export class ClientActions {
constructor(
private _ngRedux: NgRedux<IAppState>,
private _client: ClientService) {}
addClient = (client) => {
return this._client.getNextClientId().then(clientId => {
return this._ngRedux.dispatch({
type: CLIENT_ADDED,
payload: {
company: client.company,
email: client.email,
active: client.active
}
});
});
};
}
/***
* Component Example
***/
/***
* The decorator "changeDetection: ChangeDetectionStrategy.OnPush"
* is used here so if the store is changed the component state will be
* automatically updated.
***/
@Component({
selector: 'client-component',
template: TEMPLATE,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [ ClientActions ] // Actions are injected as a provider.
})
export class Clients {
/***
* Build the component out using reactive form. Don't use template driven forms as they
* enable bi-directional data binding which can lead to mutability.
* Do not mix ngModel with reactive forms!
***/
/***
* @select() provides access to the data store.
***/
@select() client$: Observable<IClients>; // <-- Data flowing down from the store
// forms items
clientForm: FormGroup;
company = new FormControl('', Validators.required);
email = new FormControl('', Validators.required);
active = new FormControl('false');
/***
* We need inject actions and the state into the
* component to make them available.
*
* @param _ngRedux
* @param _clientActions
* @param _fb
***/
constructor(private _ngRedux: NgRedux<IAppState>,
private _clientActions: ClientActions,
_fb: FormBuilder) {
this.clientForm = _fb.group({
company: this.company,
email: this.email,
active: this.active
});
}
/***
* Calling an Action:
*
* The Form update is causing a state change.
* To let the store know that the state is changing we use an action.
***/
onSubmit() {
this._clientActions.addClient(this.clientForm);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment