Sometimes, we need reusable components which you develop once and use anywhere without any additional change.
Let's start. We will create a common directive first with @Input property to receive true or false conditionally to add and remove the CSS class accordingly, as we use the directive to extend the HTML functionality.
Step 1
Create a Directive with Angular CLI (ng g d dir_name),
- import { Directive, ElementRef, Input, OnChanges, Renderer2 } from '@angular/core';
- import { LoaderSyncService } from './loader-sync.service';
-
- @Directive({
-
- selector: '[drloader]'
- })
- export class LoaderDirective implements OnChanges {
- @Input('drloader') drloader: boolean;
- constructor(private el: ElementRef, private loader: LoaderSyncService, private renderer: Renderer2) { }
-
- ngOnChanges() {
- if (this.drloader) {
- const parent = this.renderer.parentNode(this.el.nativeElement);
- const div = this.renderer.createElement('div');
- this.renderer.addClass(div, 'divshow');
-
- const ispan: Element = this.renderer.createElement('i');
- this.renderer.addClass(ispan, 'fa');
- this.renderer.addClass(ispan, 'fa-spinner');
- this.renderer.addClass(ispan, 'fa-spin');
- this.renderer.addClass(ispan, 'center');
- this.renderer.addClass(ispan, 'loder-icon');
- this.el.nativeElement.parentElement.classList.add('positionReletive');
- const finalhtml = this.renderer.appendChild(div, ispan);
- this.renderer.appendChild(this.el.nativeElement, div);
- } else {
- Array.from(this.el.nativeElement.children).forEach(child => {
- if (child['className'] === 'divshow') {
- this.renderer.removeChild(this.el.nativeElement, child);
- }
- });
- }
- }
- }
Step 2
Add CSS class definition which will help us to use it in any size HTML element,
- .center {
- margin: auto;
- margin-left: 680px;
- }
-
- .loder-icon {
- position: absolute;
- font-size: 54px;
- color: red;
- left: 50%;
- top:50%;
- margin-top: -20px;
- margin-left: -20px;
- }
-
- .positionReletive {
- width:100%;position:relative;
- }
-
- .divshow {
- display: block;
- }
-
- .divhide {
- display: none;
- }
Step 3
Use the custom directive in to HTML with isLoader=true and false below,
- <div style="width:100%;" class="bd">
- <h3 [drloader]="isLoader">My content with width:100% :
- {{tempData | json}}
- </h3>
- </div>
-
- <div style="width:50%;" class="bd">
- <h3 [drloader]="isLoader">My content with width:50% :
- {{tempData | json}}
- </h3>
- </div>
-
- <div style="width:25%;" class="bd">
- <h3 [drloader]="isLoader">My content :
- {{tempData | json}}
- </h3>
- </div>
Step 4
Let's check the output with 100% and 50% width div's. No matter what the div size is the loader icon will display at the center of div content.