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({
- // tslint:disable-next-line:directive-selector
- 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');
- // tslint:disable-next-line:label-position
- 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);
- }
- });
- }
- }
- }


sunny chauhanPosted Apr 26, 2019, 12:05 AM
Nice practical explanation , It really helps.