As we can see, EntityStateAdapter has methods for the full CRUD. Let's look at adding the capability to add a user to our component. We need to make the following additions to our component:
- Add an input field
- Dispatch an ADD_USER action with our new user as payload
The required code changes are in bold, as follows:
// app.component.ts - adding the capability to add users
import { Component } from "@angular/core";
import { AppState } from "./app-state";
import { Store } from "@ngrx/store";
import { map } from "rxjs/operators";
@Component({
selector: "app-root",
template: `
<div style="border: solid 1px black; padding: 10px;"
*ngFor="let user of users$ | async">
{{ user.name }}
</div>
<div>
<input [(ngModel)]="user" /> <button (click)="add()">Add</button>
</div>
`
})
export class AppComponent {
title = "app";
users$;
user;
id = 1;
constructor(private store: Store<AppState>) {
this.users$ = this.store
.select(state => state.users.entities)
.pipe(map(this.toArray));
this.users$.subscribe(data => console.log("users", data));
}
toArray(obj) {
const keys = Object.keys(obj);
return keys.map(key => obj[key]);
}
add() {
const newUser = { id: this.id++, name: this.user };
this.store.dispatch({
type: "ADD_USER",
payload: newUser
});
}
}
This code demonstrates how we add an input element and connect that to the field user on our class through ngModel. We also added the add() method that dispatches a user to our reducer. Adding a user should now look like the following in the UI: