Angular PrimeNg Table with NgRx Library Example (Learn it in 32 Steps)

Srikanth
13 min readMar 12, 2023

--

Thanks for visiting my medium, this article gives you information about how to Load the data in primeng table with NgRx library.

Photo by Kelly Sikkema on Unsplash

Step 0. Hey, everyone, PrimeNg is one of my favorite libraries, and am integrating it with NgRx library and also load the data in primeng table.

Before starting the application, you need to know about PrimeNg and NgRx. If you know about these, you can ignore this step.

Basically, PrimeNg is used to develop the best user interfaces and it will give inbuilt components related to table, forms etc. Also, it will help the developer to develop the user interfaces easily.

For more visit PrimeFaces — Ultimate UI Framework

NgRx is the industrial approach to store the data and it is mostly used to store the data in the state in that way can be able to access it across the application due this we can develop the user interfaces and also pass the data across all the component hierarchy.

For more visit NgRx — @NGRX/STORE

I think you understood something, In the below example, I am going to implement PrimeNg and NgRx libraries both together to load the data in PrimeNg Table.

Please find the below steps carefully and implement PrimeNg Table using NgRx and Angular Material.

Happy Coding !!!.

So, please find the below steps “How to Integrate the Prime Ng Table with NgRx Setup”.

Step 1. Create an angular project with the below command.

ng new angular-primeng-table-with-ngrx-example

Step 2. After successful creation of the angular app, change the file directory to project-name. “cd angular-primeng-table-with-ngrx-example”

Open the project in vs code using “code .” in terminal or open with vs code. Then run the project using “ng serve” in the terminal. Open project in chrome using localhost:4200.

Step 3. Open the app component in vs code and remove the content which is created by angular CLI while creating the app. For adding the PrimeNg library please follow the below commands.

npm install primeng --save
npm install primeicons --save
npm install font-awesome --save

Step 4. After that open the angular.json file and add PrimeNg Styles like below.

Step 5. Open the package.json file and changes the versions of PrimeNg accordingly.

Step 6. Do npm install and ng serve and open the application in the browser by using localhost:4200. You will find the below error.

Step 7. For solving the above error, I did some research, and I found the below libraries to install.

npm install chart.js --save
npm install quill --save
npm install @fullcalendar/core --save

Step 8. After installing the above libraries do npm install and ng serve. Open the app in the browser and see the changes if still, an error occurs please check all the above steps once again.

Step 9. Prime Ng provides flex concept in the form of one library i.e., primeflex. Am very much interested to install this library. If you are not interested, please ignore this step.

Use the below command to install the prime flex.

npm install primeflex --save

Step 10. Open the angular.json file and add the below CSS for prime flux.

If you want to know more about primeflex please click on this link https://www.primefaces.org/

If you want to know more about PrimeNg, please click on this link https://www.primefaces.org/.

Step 11. After that create a shared library under the src/libs folder by using the below command.

ng generate module shared

Step 12. Open app.module.ts and import SharedModule and add inside imports array.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SharedModule } from '../libs/shared/shared.module';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
SharedModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Step 13. In this project, I am using Prime Ng cards to display data in the form of cards. For that, Open shared.module.ts, Import CardModule, TableModule, BottomModule, and it into both import and export array. In that way, you can import the shared module into any module.

The shared module is not for only importing and exporting one module. You can add multiple modules in the import and export array. For this project alone, I added only one module.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ButtonModule, CardModule, TableModule } from 'primeng';
@NgModule({
declarations: [],
imports: [
CommonModule,
CardModule,
TableModule,
ButtonModule
],
exports:[
CardModule,
TableModule,
ButtonModule
]
})
export class SharedModule { }

Step 14. Oops !!!, Not added NgRx, for adding NgRx please follow the below steps.

Step 15. For adding “NgRx library” by using the command and install all libraries along with “@ngrx/Store” like @ngrx/effects @ngrx/store-devtools @ngrx/schematics, please find the command below.

Install all in once
npm install @ngrx/store @ngrx/effects @ngrx/store-devtools @ngrx/schematics --save

(OR)

Install one after another

npm install @ngrx/store
npm install @ngrx/effects
npm install @ngrx/store-devtools
npm install @ngrx/schematics

Step 16. Change default “angular cli” to “NgRx cli” to install actions, reducers, and effects.

Don’t worry it won’t affect any angular-related commands.

ng config cli.defaultCollection @ngrx/schematics

Step 17. To generate store, state, and reducers setup please run the below command and give the root module to “app.module.ts”.

ng generate store AuditState --root --module app.module.ts

While running the above command am getting this error.

For solving this error, I was changed the NgRx versions inside package.json as below.

After changing the versions, the command is executed successfully.

Step 18. After executing the above command reducers folder will be created and the “index.js” file will be there.

And Also, Inside the “app.module.ts” file imports array is updated with new lines of code.

The auto-generated “index.js” file will be like the below. In this “index.js” the state and reducer will be added by default after performing the above command.

Step 19. Please run the below commands to generate actions, effects, selectors, and reducers.

 ng generate action actions/audits
ng generate reducer reducers/audits
ng generate effect effects/audits
ng generate selector selectors/audits

Attached screenshot of the terminal window in which I ran the commands to generate action, effects, selectors, and reducers.

Step 20. So, the NgRx schematics are generated automatically with a few files contains with sample data, please find below the files.

  • Actions are in the sense calling the actions like run, catch, drop. For this project, we need audits data, so I created loadAudits to get the audits and loadAuditsSuccess for storing data, and loadUsersFailure action to store the error.
  • Effects are like interceptors/listeners whenever we are dispatching the action. At that time effect will be triggered and it will call the service, If the service gives a response, we will call the success action.

If it returns an error, we will call the failure action.

  • Reducers are mainly used for updating the store based on the actions.
  • Selectors are used to get the data from the updated state. the updated state will be available on the side of the reducer.

Step 21. After successfully generating all the files. Create Audit models for Audit state in app/store/models/ folder.

After completing this, please do “npm install” and after running the application by using “ng serve”.

If in case any error is found while running the application, please open the “package.json” file. Check the “NgRx versions” and “angular version” is the same or not. If it is not the same, please change the version like below. If no errors this process is not required.

After that check the app.module.ts file and change the effect statement forFeature to forRoot like below.

Step 22. Open app.module.ts and add below statement inside imports array to load redux dev tools in the application local environment to check the redux values. If it is already available, please ignore this point.

!environment. production? StoreDevtoolsModule.instrument() : []

If you don’t know how to install chrome dev tools click on this link and click on add to chrome. If already did this one, please ignore it.

Open the project by using “localhost:4200” and inspecting it you can be able to see redux dev-tools with no state information.

Step 23. Open the “audits.action.ts” file and add the below actions. If the “ng generate action actions/users” command generated actions by default,

You can ignore this step. If you want to add new actions, you can use them.

Step 24. Open the “index.ts” file from “app/store/reducers” and add the below changes.

  • First, import the Audit reducer in index.js by using the below statement.
import * as fromAuditReducer from './audits.reducer';
  • Add State of AuditReducer in state interface like below. In the same way, we can add multiple states as of now we are adding only one.
export interface State {
audits : fromAuditReducer.State;
}
  • Add reducer in ActionReducerMap, the same way we can add multiple reducers as of now we are adding only one.
export const reducers: ActionReducerMap<State> = {
audits : fromAuditReducer.reducer
};

Please find the overall file of index.ts for the test if you miss the code.

After successfully adding the above step, you can ably see the changes in the redux dev tools, for that, you need to run the application and go chrome dev tool so that you can be able to see the redux tab and you will see the empty state object.

Before going to next step, we need to update the existing actions, why because it is generated by command line, and I want to add the extra parameters as per the functionality.

Step 25. Open the “audits.reducers.ts ” file and add the below changes.

  • Import user’s actions by using the below statement in the side “audits.reducers.ts” file.
import * as AuditAuctions from "../actions/audits.actions";
  • Add data types in the side State interface like below.
export interface State{
loading: boolean;
errors: any;
audits: any[];
totalItems: number;
pageIndex: number;
pageSize: number;
}
  • Declare properties with default values inside the state object.
export const initialState: State = {
loading: false,
errors: null,
audits: [],
totalItems: 0,
pageIndex: 0,
pageSize: 10
};
  • Add actions inside the reducer function to update the state based on the action type.
export const reducer = createReducer(
initialState,
on(AuditAuctions.loadAuditss, (state,{pageIndex,pageSize}) => ({
...state,
loading:false,
error:null,
pageIndex,
pageSize
})),
on(AuditAuctions.loadAuditssSuccess, (state, { data }) => ({
...state,
audits:data.audits,
loading: true,
totalItems:data.totalCount,
error: null
})),
on(AuditAuctions.loadAuditssFailure, (state,{error}) => ({...state,loading: false, error})),
);
  • After changing all these the overall file will look like the below.

Open the application and go to chrome dev tools click on the redux tab, you will see the values inside audits object in redux dev tools.

Up to everything clear right, if anything did wrong, please check from first.

Step 26. Open the audits.selector.ts file and add the below lines of code to read data from the store.

  • First import AuditReducer by using the below statement.
import * as fromAuditReducer from '../reducers/audits.reducer';
  • To get the state object from audit reducer please add the below statement.
export const getAuditsState = createFeatureSelector<fromAuditReducer.State>('audits');
  • Add the below methods to get specific data from the store.
export const loading = createSelector(
getAuditsState,
(state: fromAuditReducer.State) => state.loading
);

export const getAudits = createSelector(
getAuditsState,
(state: fromAuditReducer.State) => state.audits
);

export const getTotalItems = createSelector(
getAuditsState,
(state: fromAuditReducer.State) => state.totalItems
);
  • The Overall file of audits.selectors.ts looks like the below please check if you miss anything or not.

Step 27. After all these do we need to add the changes in effects before that we need to create one service.

Create Audits Service under the “apis/” folder and add the below lines of code.

  • To generate a service file please use the below command and also add HttpClientModule inside “app. module.ts”.
ng generate service apis/audits.
  • Open the audits.service.ts file and add the below lines of code to call the service to get all audits.
private headers:HttpHeaders= new HttpHeaders({
'Content-Type':'application/json',
'Accept':"application/json",
'Access-Control-Allow-Methods':'GET,POST,PUT,DELETE',
'Authorization':''
});

constructor(private http:HttpClient) { }

public loadAudits(pageIndex,pageSize){
return this.http.get(`http://localhost:3000/public/audits/${pageIndex}/${pageSize}`,{headers :this.headers})
}

The overall file of audits.service.ts looks like the below, please check twice if you miss anything.

Step 28. Open the audits.effect.ts file and add the below lines of code.

  • Import Audits Service and add as a dependency in the constructor, also import Audit actions inside the effects.
import { Injectable } from '@angular/core';
import { Actions, createEffect } from '@ngrx/effects';
import { AuditsService } from '../apis/audits.service';

@Injectable()
export class AuditsEffects {
constructor(private actions$: Actions, private auditsService: AuditsService) { }
}
  • Create load audits effect and add below lines of code inside that effect to call the audits service whenever the action is called and it will call effect, once the responce or error came from service it will call the other actions.
 loadAudits$ = createEffect(() =>
this.actions$.pipe(
ofType(AuditsActions.loadAuditss),
map((action: any) => action),
mergeMap((action: any) => {
return this.auditsService.loadAudits(action.pageIndex, action.pageSize).pipe(
map(data => AuditsActions.loadAuditssSuccess({ data })),
catchError(error => of(AuditsActions.loadAuditssFailure({ error })))
);
})
)
)
  • The Overall file of audits.effects.ts looks like the one below.

Step 29. Finally, we completed all the parts of code related to NgRx Store except dispatching the action and showing data in the UI.

Step 30. Open the “app.component.ts” file, to load data and display data in the component. Please add the below lines of code.

  • Import store form store module and add it as a dependency in the constructor by using the below lines of code.
import { Component,OnInit } from '@angular/core';
import { Store } from '@ngrx/store';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'angular-primeng-table-with-ngrx-example';

constructor(private readonly store: Store){
}

ngOnInit(): void {
}
}
  • Import Audit actions by using the below statements.
import * as AuditsActions from "./actions/audits.actions";
  • To call the action by using store dispatch method as below.
  pageSize = 10;

constructor(private readonly store: Store) {
this.store.dispatch(AuditsActions.loadAuditss({ pageIndex: 0, pageSize: this.pageSize }));
}
  • After that import selectors by using the below statement and declare the audits$ variable to store data inside audits.component.ts.
import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import * as AuditsActions from "./actions/audits.actions";
import * as AuditsSelectors from "./selectors/audits.selectors";

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'angular-primeng-table-with-ngrx-example';
pageSize = 10;
audits$: any;
totalItems$: any;

constructor(private readonly store: Store) {
this.store.dispatch(AuditsActions.loadAuditss({ pageIndex: 0, pageSize: this.pageSize }));
}

ngOnInit(): void {
this.audits$ = this.store.select(AuditsSelectors.getAudits);
this.totalItems$ = this.store.select(AuditsSelectors.getTotalItems);
}
}

Once all the above points are completed, Open the application in the browser window and inspect the browser window click on the redux tab, you can be able to see the data inside redux dev tools as below.

Note: If you not started related backend server to call the api, please start it first and after running the angular application.

Step 31. Looks like we added all the changes related to NgRx library and also data is fetching from server. Next will add the primeng table related code to load data in primeng table.

First create the below variable cols to store the header and field information. Here header means column header and field means column value.

Step 32. Oops!!!, we have not added HTML content. Add HTML content for displaying the table as below.

Booyah !!!, Finally we integrated PrimeNg with NgRx library. But I need to add the paginator in this below table but in primeng library the adding paginator it would be some tricky. I will add soon the primeng paginator in new article (It will cover both table and paginator). Apologies for inconvenience.

Open application in chrome you can be able to see the data in primeng table as below.

Final Output

Thanks for reading my article, please share your feedback, claps, and comments. In that way, it will have helped me to improve my articles in the future. Please share my story with your near and dear, also follow and subscribe to the medium.

--

--

Srikanth

Senior Software Engineer | Medium Articles | Storyteller | Quick Learner | React JS | Angular | Java | Learn Something new from my stories