how to get and display ngrx store data in angular using ngFor

Viewed 2670

I am storing form data in the array in state.I am receiving the array but its in nested form .I don't know how to display it.

//view Viewcomponent.ts

customerarray: Customer[];
ngOnInit() {
// this.customerObs = this.store.select('customerList');
this.store.select<Customer[]>('customerList').subscribe(res =>                     
    {
      this.customerarray = res;
      console.log(res);
      console.log(this.customerarray);
    });
}

//viewcomponent.html

<li *ngFor="let customer of customerarray; i as index">
      <span>{{ i + 1}}.</span>  {{customer.customer.name}}
</li>

//reducer.ts

import { Customer } from '../app/models/customer';
import { ADD_CUSTOMER } from '../app/store/action';
import * as CustomerAction from '../app/store/action';
const initialState = {
    customer: [
        new Customer('Steve', 'Yellow'),
        new Customer('RDJ', 'Red')
    ]
};

export function CustomerReducer(state = initialState, action: CustomerAction.AddCustomer) {
    console.log(state.customer);
    switch (action.type) {
        case CustomerAction.ADD_CUSTOMER:
            return {`enter code here`

            ...state,                
            customer: [...state.customer, action.payload]
            };

        default:
            return state;
    }
}
2 Answers

I think that is a change detection issue. Your component doesn't render on this subscricption.

try this -

.ts file -

customersObs:Observable<Customer[]>
constructor() {
 this.customersObs = this.store.select<Customer[]>('customerList');
}

.html file -

<li *ngFor="let customer of cusomersObs | async; i as index">
      <span>{{ i + 1}}.</span>  {{customer.name}}
</li>

I am assuming that you Customer class is defined like this -

export class Customer {
  name: string;
  color: string;
  constructor(n: string, c: string) {
     this.name = n;
     this.color = c;
  }
}

I am also assuming that your selector this.store.select<Customer[]>('customerList') returns the customer property from your initialState.

If I am correct then you should update your template like this -

<li *ngFor="let customer of customerarray; i as index">
      <span>{{ i + 1}}.</span>  {{customer.name}}
</li>
Related