I am new to NGXS and trying to integrate it into a small project. The only problem is that there are no good examples of a search / filter on state.
My app gets a list of products from a backend API. It shows them by SKU on the page. I want the user to be able to type in an SKU in the input field and have the list automatically filter products as the user types.
products.state.ts:
@Selector()
static getProductList(state: ProductStateModel) {
return state.products;
}
@Selector()
static prodFilter(searchObj: any[]) {
// something needs to happen here in order to filter state
}
products.component.ts:
@Select(ProductState.getProductList) products: Observable<Product[]>;
filterForm = this.fb.group({ sku: null });
constructor( private store: Store, private fb: FormBuilder ) { }
ngOnInit() {
this.store.dispatch( new GetProducts() );
}
//something in here (ngOnInit? ngOnChanges?) to pass (cloned??) product state into selector??
products.component.html:
<form
[formGroup]='filterForm'
novalidate
ngxsForm='products.filterForm'
(ngSubmit)='onSubmit()'
>
<input type='number' formControlName='sku' />
<button type='submit'>Submit</button>
</form>
<mat-accordion class='product-accordion'>
<mat-expansion-panel *ngFor='let product of products | async'>
<mat-expansion-panel-header>
SKU: {{ product.sku }}
</mat-expansion-panel-header>
<p>${{ product.price }}</p>
<p>{{ product.description }}</p>
</mat-expansion-panel>
</mat-accordion>
I have so many questions. I believe that I shouldn't be mutating the products state directly so would I clone it? Would the HTML output change then? Should I create a new state.ts file for the filtered products?
Any help would be much appreciated (especially a stackblitz example)!