Skip to content

Instantly share code, notes, and snippets.

@cyberdante
Created September 20, 2017 14:54
Show Gist options
  • Save cyberdante/c20e3c7a448921c962b39fdb0d41786a to your computer and use it in GitHub Desktop.
Save cyberdante/c20e3c7a448921c962b39fdb0d41786a to your computer and use it in GitHub Desktop.
Angular 4 directive for disabling other DOM elements that don't have a native disabled attribute without using pointer-events: none (to support IE <11)
import { Directive, ElementRef, Input, Renderer } from '@angular/core';
import { NgControl, FormControl } from '@angular/forms';
@Directive({
selector: '[ng-disable]'
})
export class NgDisableDirective {
@Input('ng-disable') public isDisabled: boolean = false;
private control: FormControl = new FormControl('');
private wrapper;
private divElement;
constructor(protected el: ElementRef, private renderer: Renderer) {
this.wrapper = this.renderer.createElement(this.el.nativeElement.parentNode, 'div');
this.divElement = this.renderer.createElement(this.wrapper, 'div');
this.divElement.style.position = 'absolute';
this.divElement.style.opacity = '0.02';
this.divElement.style.zIndex = 250;
this.divElement.style.backgroundColor = 'white';
this.wrap(this.el.nativeElement, this.wrapper);
}
ngDoCheck() {
this.disable();
}
disable() {
if (this.isDisabled) {
let parentElement: any = this.el.nativeElement.parentNode;
let element: any = this.el.nativeElement;
element.style.opacity = 0.7;
element.style.cursor = 'default';
element.style.textdecoration = 'none';
// element.style.pointerevents = 'none'; this does not work on IE < 11
// workaround pointer-events for IE9
this.divElement.style.width = parentElement.offsetWidth + 'px';
this.divElement.style.height = parentElement.offsetHeight + 'px';
this.divElement.style.offsetTop = parentElement.offsetTop;
this.divElement.style.offsetLeft = parentElement.offsetLeft;
}
}
wrap(el: Element, wrapper: Element) {
el.parentNode.insertBefore(wrapper, el);
wrapper.appendChild(el);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment