Created
July 21, 2017 15:06
-
-
Save genuinefafa/12e95e0de43869851d57eb08ecf6b332 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, ElementRef, Renderer2, HostListener, Input } from '@angular/core'; | |
import { OnDestroy, AfterContentInit } from '@angular/core'; | |
@Directive({ | |
selector: '[appAnchoEnFoco]' | |
}) | |
export class AnchoEnFocoDirective implements OnDestroy, AfterContentInit { | |
private _focused = false; | |
private _listenFocus; | |
private _listenBlur; | |
@Input() appAnchoEnFoco: string; | |
constructor(private el: ElementRef, private renderer: Renderer2) {} | |
ngAfterContentInit() { | |
const nativeElement: Element = this.el.nativeElement as Element | |
const inputElement: Element = nativeElement.getElementsByTagName('input')[0] | |
console.log('inputElement', inputElement); | |
if (inputElement) { | |
this._listenFocus = this.renderer.listen(inputElement, 'focus', (event) => { | |
this.onFocus(); | |
}) | |
this._listenBlur = this.renderer.listen(inputElement, 'blur', (event) => { | |
this.onBlur(); | |
}) | |
} | |
} | |
ngOnDestroy() { | |
if (this._listenFocus) { | |
this._listenFocus(); | |
} | |
if (this._listenBlur) { | |
this._listenBlur(); | |
} | |
} | |
// indica el estilo de ancho a aplicar cuando se selecciona | |
@HostListener('mouseenter') onMouseEnter() { | |
this.agrandarAncho(); | |
} | |
@HostListener('mouseleave') onMouseLeave() { | |
if (!(this._focused)) { | |
this.recuperarAncho(); | |
} | |
} | |
@HostListener('focus') onFocus() { | |
this._focused = true; | |
this.agrandarAncho(); | |
} | |
@HostListener('blur') onBlur() { | |
this._focused = false; | |
this.recuperarAncho(); | |
} | |
private recuperarAncho() { | |
const nativeElement: Element = this.el.nativeElement; | |
const parentElement = nativeElement.parentElement; | |
parentElement.classList.remove(this.appAnchoEnFoco); | |
} | |
private agrandarAncho() { | |
const nativeElement: Element = this.el.nativeElement; | |
const parentElement = nativeElement.parentElement; | |
parentElement.classList.add(this.appAnchoEnFoco); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment