Implementation

Let’s see how we can implement the idle timeout feature in the Angular application with the ng-idle library. As a first step, we need to install ng-idle dependencies in the existing application.

npm install --save @ng-idle/core @ng-idle/keepalive angular2-moment

Once installed we have to import these modules in the app.module.ts file.

app.module.ts

Since AppComponent is the main/bootstrap component in the Angular application, we need to implement this logic in it. We are setting the Idle time 5 seconds which means we will get a warning message after 5 seconds of inactivity and timeout as 5 seconds which means it will be timed out within another 5 seconds.

I set both idle time and timeout time to 5 seconds for the demonstration purpose. Usually, these times are longer in the actual environments, typically it is around 15 mins.

app.component.ts

I want to show a modal window whenever the user is idle and give some options for the user to logout or stay as shown in the figure.

the modal window for the idle timeout

For this, we are using ngx-bootstrap modal service. We need to import this in app.module.ts and place the html in the app.component.html file

// import this in app.module.ts

import { ModalModule } from 'ngx-bootstrap/modal';

app.component.html

Along with this, we don’t want to watch the user when they are not logged in. For this, I created a service and userLoggedIn subject which can be subscribed to see the user is logged in or not. Below is that service

app.service.ts

Whenever the user logs in, we are calling appService setUserLoggedIn method to set the flag true.

login.component.ts

Here is the complete app.component.ts file. If you look at line 67 we are subscribing for the userLoggedIn subject from the service to see the user is logged in or not and decides whether to watch or not for the user inactivity. Notice BsModalService and AppService are injected into the app component constructor and lines 44, 54 where we are hiding and showing modal window according to the user activity.

complete app.component.ts

You can download the complete working example from here.