Block UI in Angular 4/5/6 Example

Block UI in Angular 4/5/6 Example

Block UI in Angular 4 Example:

In our last post, I have explained how to use ng-spin-kit spinner component to display loading/spinner icons. But it was not blocking the UI, so user may abrupt while loading the data.

So it is highly recommended to block the UI whenever some data loading happening to avoid unexpected system behaviours.

ng-block-ui is the best available angular component to block ui in angular 4.

 

Step 1: Install ng-block-ui

[plain]

// Angular 2.x
npm install ng-block-ui –save

— or —

// Angular 4.x
npm install ng-block-ui@next –save

[/plain]

 

Step 2: Import BlockUIModule to your module

 

import { BlockUIModule } from 'ng-block-ui';

@NgModule({
imports:[BlockUIModule],
declarations:[]
})

 

Step 3: Import BlockUI, NgBlockUI to your component

 


import { BlockUI, NgBlockUI } from 'ng-block-ui';

export class myComponent{
// Decorator wires up blockUI instance
@BlockUI() blockUI: NgBlockUI;

constructor(private userService: UserService, private couponService : CouponService){
// starting to block
this.blockUI.start('Loading Coupons...');
this.myService.getAllData().subscribe(
response =>
{
// my business logics here

// stopping the block here
this.blockUI.stop();
}
)
}

}

 

Step 4: Wrap up the contents where you need block

 

I am just wrapping the table here. If you want the full page to block then wrap container or row bootstrap classes if you are using bootstrap. Else equivalent place where you want to block.

[plain]

<block-ui>
<table class=”table table-striped” [mfData]=”coupons” #mf = “mfDataTable” [mfRowsOnPage]=”10″>
<thead class=”thead-inverse”>
<tr>
</tr>
</thead>
<tbody>
</tbody>
</table>
</block-ui>

[/plain]

 

Additional Options:

Delay start and stop:

When blocking with fast service calls the block overlay can flicker for a small amount of time. To prevent this a delayStart and a delayStop can be configured to prevent this scenario.

Delay Description
delayStart: number Waits given amount of milliseconds before starting to block.
delayStop: number Waits given amount of milliseconds before stopping current block.

 

Blocking only particular div:

HTML Template:


<div *blockUI="'contact-list'">
<!-- List markup -->
</div>

Typescript:

<div><!-- List markup --></div>
// Pass instance name to decorator
@BlockUI('contact-list') blockUIList: NgBlockUI;

 

Block UI in Angular 4 Example

 

Pros of ng-block-ui:

  1. Simple to use
  2. Easy to understand
  3. More customization options provided like selecting only particular div to block / showing loading or any other images on top of block ui (custom templates) etc.
  4. Supports both angular 2 and angular 4.

 

Github link

4,175 total views, 9 views today

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.