Skip to content

Instantly share code, notes, and snippets.

@genuinefafa
Created July 21, 2017 15:06
Show Gist options
  • Save genuinefafa/12e95e0de43869851d57eb08ecf6b332 to your computer and use it in GitHub Desktop.
Save genuinefafa/12e95e0de43869851d57eb08ecf6b332 to your computer and use it in GitHub Desktop.
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