@angular/core#HostListener TypeScript Examples

The following examples show how to use @angular/core#HostListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: leaderboard.component.ts    From one-platform with MIT License 6 votes vote down vote up
/**
   * This is used to check application filter multi-select dropdown closing
   * Reference: https://medium.com/ekohe/dismissing-a-react-dropdown-menu-by-clicking-outside-its-container-7fe9f31a6767
   */
  @HostListener('document:click', ['$event'])
  onDocClick(ev: Event) {
    const pickSelect = this.pickSelect?.nativeElement;
    if (
      pickSelect &&
      !pickSelect.contains(ev.target) &&
      this.isPickSelectOpen
    ) {
      console.log('hit');
      this.onPickedLeaderboardCategoryClose();
    }
  }
Example #2
Source File: base.component.ts    From 1hop with MIT License 6 votes vote down vote up
@HostListener('window:beforeinstallprompt', ['$event'])
    onbeforeinstallprompt(e) {

        e.preventDefault();

        this.deferredPrompt = e;

        if (
            !localStorage.getItem('showInstall') ||
            localStorage.getItem('showInstall') === 'true'
        ) {

            this.showInstall = true;
        }
    }
Example #3
Source File: base.component.ts    From 1x.ag with MIT License 6 votes vote down vote up
@HostListener('window:beforeinstallprompt', ['$event'])
    onbeforeinstallprompt(e) {

        e.preventDefault();

        this.deferredPrompt = e;

        if (
            !localStorage.getItem('showInstall') ||
            localStorage.getItem('showInstall') === 'true'
        ) {

            this.showInstall = true;
        }
    }
Example #4
Source File: clipboard.directive.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
@HostListener('click')
  copyToClipboard(): void {
    if (!this.textToCopy) {
      return;
    }

    try {
      this.clipboardService.copyToClipboard(this.textToCopy);
      this.copied.emit(this.textToCopy);

      this.nzMessageService.success(this.translateService.instant('SUCCESS_MESSAGE.COPIED_TO_CLIPBOARD'));
    } catch (e: any) {
      this.nzMessageService.error(this.translateService.instant('ERROR_MESSAGES.UNEXPECTED_ERROR'));
    }
  }
Example #5
Source File: token-amount.directive.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
@HostListener('ngModelChange')
  private onChange(): void {
    const nativeValue: string = this.elementRef.nativeElement.value || '';
    let value = nativeValue.replaceAll(',', '');

    let caretPosition = this.elementRef.nativeElement.selectionStart;

    if (nativeValue && nativeValue[nativeValue.length - 1] === ',') {
      value += '.';
    }
    if (value === '.') {
      if (this.prevValue === '') {
        value = '0.';
        caretPosition = 2;
      } else {
        value = '';
        caretPosition = 0;
      }
    }

    if (this.amountRegex.test(value)) {
      value = this.getNewValue(value);
      if (value === this.prevValue) {
        caretPosition = this.prevCaretPosition;
      } else {
        caretPosition = this.getNewCaretPosition(value, caretPosition);
      }
    } else {
      value = this.prevValue;
      caretPosition = this.prevCaretPosition;
    }

    this.elementRef.nativeElement.value = value;
    this.elementRef.nativeElement.setSelectionRange(caretPosition, caretPosition);
    this.amountChange.emit(value);

    this.prevValue = value;
    this.prevCaretPosition = caretPosition;
  }
Example #6
Source File: modal.component.ts    From canopy with Apache License 2.0 6 votes vote down vote up
// onOverlayClick and onModalClick add the following functionality:
  // clicking outside the modal closes the modal unless specified
  // otherwise using closeOnOverlayClick.
  // We specifically listen to the `mousedown` event because with
  // the `click` event a user could click inside the modal and
  // drag the mouse on the overlay causing the modal to close.
  @HostListener('mousedown') onOverlayClick(): void {
    this.modalService.close(this.id);
  }
Example #7
Source File: click-outside-same-class.directive.ts    From mylog14 with GNU General Public License v3.0 6 votes vote down vote up
@HostListener('document:click', ['$event'])
  public onDocumentClick(event: MouseEvent): void {
    const targetElement = event.target as HTMLElement;

    // Check if the click was outside the elements with the same class
    if (targetElement && !this.elementRef.nativeElement.classList.contains(targetElement.className)) {
      this.clickOutside.emit(event);
    }
  }
Example #8
Source File: chat-form.component.ts    From qd-messages-ts with GNU Affero General Public License v3.0 6 votes vote down vote up
@HostListener('drop', ['$event'])
  onDrop(event: any) {
    if (this.dropFiles) {
      event.preventDefault();
      event.stopPropagation();

      this.fileOver = false;
      if (event.dataTransfer && event.dataTransfer.files) {

        for (const file of event.dataTransfer.files) {
          const res = file;

          if (this.imgDropTypes.includes(file.type)) {
            const fr = new FileReader();
            fr.onload = (e: any) => {
              res.src = e.target.result;
              res.urlStyle = this.domSanitizer.bypassSecurityTrustStyle(`url(${res.src})`);
              this.cd.detectChanges();
            };

            fr.readAsDataURL(file);
          }
          this.droppedFiles.push(res);
        }
      }
    }
  }
Example #9
Source File: mermaid-viewer.component.ts    From visualization with MIT License 6 votes vote down vote up
@HostListener('body:wheel', ['$event'])
  public refreshZoom2(e: WheelEvent): void {

    this.scale += (-e.deltaY / 100);

    if (this.scale < 0.1) {
      this.scale = 0.1;
    }

    if (this.scale > 4) {
      this.scale = 4;
    }
    this.viewBox.next(this.viewBox.value);
  }
Example #10
Source File: ngx-gallery-image.component.ts    From ngx-gallery-9 with MIT License 6 votes vote down vote up
@HostListener('mouseenter') onMouseEnter() {
      if (this.arrowsAutoHide && !this.arrows) {
          this.arrows = true;
      }

      if (this.autoPlay && this.autoPlayPauseOnHover) {
          this.stopAutoPlay();
      }
  }
Example #11
Source File: app.component.ts    From scion-microfrontend-platform with Eclipse Public License 2.0 6 votes vote down vote up
@HostListener('document:keydown', ['$event'])
  @HostListener('document:keyup', ['$event'])
  public async onPropagatedKeyboardEvent(event: KeyboardEvent): Promise<void> {
    // only log propagated keyboard events, i.e., keyboard events propagated across iframe boundaries.
    if (!event.isTrusted && (event.target as Element).tagName === 'SCI-ROUTER-OUTLET') {
      const outletContextName = (await this._outletContext)?.name ?? 'n/a';
      console.debug(`[AppComponent::document:on${event.type}] [SYNTHETIC] [outletContext=${outletContextName}, key='${event.key}', control=${event.ctrlKey}, shift=${event.shiftKey}, alt=${event.altKey}, meta=${event.metaKey}]`);
    }
  }
Example #12
Source File: emote-card.component.ts    From App with MIT License 6 votes vote down vote up
/**
	 * Middle Mouse Click: open in new tab
	 */
	@HostListener('auxclick', ['$event'])
	onMiddleClick(ev: MouseEvent): void {
		if (ev.button === 1) {
			const url = this.router.serializeUrl(this.router.createUrlTree(['/emotes', String(this.emote?.getID())]));

			this.windowRef.getNativeWindow()?.open(url, '_blank');
		}
	}
Example #13
Source File: rich-tooltip.directive.ts    From colo-calc with Do What The F*ck You Want To Public License 6 votes vote down vote up
@HostListener('mouseenter') public onMouseEnter() {
    this.timeout = setTimeout(() => {
      this.tooltipService.showTooltip(this.character, this.summon, this.pos);
      this.timeout = null;
    }, 500)

    const interval = setInterval(() => {
      if (!document.body.contains(this.el.nativeElement)) {
        this.clearTooltip();
        clearInterval(interval);
      }
    }, 300)
  }
Example #14
Source File: select.component.ts    From ng-event-plugins with Apache License 2.0 6 votes vote down vote up
// Only react to Esc if dropdown is open
    @shouldCall((_, open) => open)
    @HostListener('keydown.esc.init', ['$event'])
    @HostListener('keydown.esc.silent', ['$event', 'open'])
    onEsc(event: KeyboardEvent) {
        event.stopPropagation();
        this.input.nativeElement.focus();
        this.open = false;
    }
Example #15
Source File: app.component.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
@HostListener("mousewheel", ["$event"])
  public async handleMouseWheelEvent(event: WheelEvent): Promise<void> {
    if (!event.ctrlKey) {
      return;
    }

    try {
      if ((event as any).wheelDelta > 0) {
        await this._zoomService.applyZoom(ZoomDirection.ZoomIn);
      } else {
        await this._zoomService.applyZoom(ZoomDirection.ZoomOut);
      }
    } catch (e) {
      console.error(e);
    }
  }
Example #16
Source File: formatter.directive.ts    From svg-path-editor with Apache License 2.0 6 votes vote down vote up
@HostListener('input', ['$event'])
  onInput(e: InputEvent) {
    let value = '';
    if (this.formatterType === 'float') { value = this.viewValue.replace(/[\u066B,]/g, '.').replace(/[^\-0-9.eE]/g, ''); }
    if (this.formatterType === 'integer') { value = this.viewValue.replace(/[^\-0-9]/g, ''); }
    if (this.formatterType === 'positive-float') { value = this.viewValue.replace(/[\u066B,]/g, '.').replace(/[^0-9.eE]/g, ''); }
    if (this.formatterType === 'positive-integer') { value = this.viewValue.replace(/[^0-9]/g, ''); }

    this.viewValue = value;
    const floatValue = parseFloat(value);
    if (!isNaN(floatValue)) {
      this.valueChange.emit(floatValue);
      this.internalValue = floatValue;
    }
  }
Example #17
Source File: image-viewer.component.ts    From nghacks with MIT License 6 votes vote down vote up
@HostListener('window:resize', ['$event'])
  private setImageDimension(): void {

    if (!isPlatformBrowser(this._platformId)) { return; }

    const windowDimension = new ImageDimension(
      this.percentage(this._document.body.clientWidth, 90),
      this.percentage(this._document.body.clientHeight, 90)
    );
    this.calculatedImageDimension = this.calculateAspectRatioFit(this._originalImageDimension, windowDimension);
  }
Example #18
Source File: temperature-dragger.component.ts    From ngx-admin-dotnet-starter with MIT License 6 votes vote down vote up
@HostListener('window:mouseup', ['$event'])
  onMouseUp(event) {
    this.recalculateValue(event);
    this.isMouseDown = false;
    if (this.changeStarted) {
      this.valueChangeCompleted.emit(this.value);
    }
    this.changeStarted = false;
  }
Example #19
Source File: tooltip-copy.directive.ts    From alauda-ui with MIT License 6 votes vote down vote up
@HostListener('click')
  async onSourceClick() {
    if (!this.disabled) {
      try {
        await navigator.clipboard.writeText(this.auiTooltipCopy);
        this.content = this.auiTooltipCopySuccessTip;
      } catch {
        this.content = this.auiTooltipCopyFailTip;
      }
    }
  }
Example #20
Source File: link-to.directive.ts    From router with MIT License 6 votes vote down vote up
/**
   * Handles click events on the associated link
   * Prevents default action for non-combination click events without a target
   */
  @HostListener('click', ['$event'])
  onClick(event: any) {
    if (!this._href) {
      return;
    }
    if (!this._comboClick(event) && this.target === DEFAULT_TARGET) {
      this.router.go(this._href, this._query, this._hash);

      event.preventDefault();
    }
  }
Example #21
Source File: image-crop.component.ts    From ASW-Form-Builder with MIT License 6 votes vote down vote up
@HostListener('window:resize')
    onResize(): void {
        if (!this.loadedImage) {
            return;
        }
        this.resizeCropperPosition();
        this.setMaxSize();
        this.setCropperScaledMinSize();
        this.setCropperScaledMaxSize();
    }
Example #22
Source File: drag-and-drop-files.directive.ts    From qbit-matUI with MIT License 6 votes vote down vote up
// Listen for dropped action
  @HostListener('drop', ['$event'])
  public onDrop(event) {
    event.preventDefault();
    event.stopPropagation();

    this.fileOver = false;

    let isValid = true;

    // Format a new $event object
    let files = event.dataTransfer?.files as any;
    let newEvent = {
      target: {
        files: files
      }
    };

    // Validate that we received only .torrent files!
    for(const file of files) {
      if(!(file.name as string).endsWith('.torrent')) { isValid = false; break; }
    }

    if(isValid && files.length > 0) {
      this.fileDropped.emit(newEvent);
    }
  }
Example #23
Source File: block.component.ts    From blockcore-explorer with MIT License 6 votes vote down vote up
@HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
    console.log(event);

    if (event.key === 'ArrowRight' || event.key === 'PageUp') {
      this.nextBlock();
    }

    if (event.key === 'ArrowLeft' || event.key === 'PageDown') {
      this.previousBlock();
    }

    if (event.key === 'Home') {
      this.navigateToBlock(1);
    }

    if (event.key === 'End') {
      this.lastBlock();
    }
  }
Example #24
Source File: block.component.ts    From blockcore-hub with MIT License 6 votes vote down vote up
@HostListener('window:keyup', ['$event'])
    keyEvent(event: KeyboardEvent) {
        // eslint-disable-next-line import/no-deprecated
        if (event.keyCode === PAGE_UP) {
            this.increment();
        }

        // eslint-disable-next-line import/no-deprecated
        if (event.keyCode === PAGE_DOWN) {
            this.decrement();
        }

        // eslint-disable-next-line import/no-deprecated
        if (event.keyCode === END) {
            this.openLatest();
        }

        // eslint-disable-next-line import/no-deprecated
        if (event.keyCode === HOME) {
            this.open(0);
        }
    }
Example #25
Source File: compose-email.component.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
//handles tabbing directly to the editor and skipping all the
  //buttons
  @HostListener('document:keyup', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
    if (event.key == 'Tab' && this.lastField == 'subject') {
      let el: any = document.querySelectorAll('.ql-editor')

      if (el && el.length == 1) {
        el[0].focus();
        this.lastField = 'body';
      }
    }
  }
Example #26
Source File: cometchat-conversation-list-with-messages.component.ts    From cometchat-pro-angular-ui-kit with MIT License 6 votes vote down vote up
/**
   * Checks when window size is changed in realtime
   */
  @HostListener("window:resize", [])
  onResize(): boolean {
    try {
      this.innerWidth = window.innerWidth;
      if (
        this.innerWidth >= enums.BREAKPOINT_MIN_WIDTH &&
        this.innerWidth <= enums.BREAKPOINT_MAX_WIDTH
      ) {
        if (this.checkIfAnimated === true) {
          return false;
        }

        this.checkAnimatedState = "normal";

        this.checkIfAnimated = true;
      } else {
        this.checkAnimatedState = null;
        this.checkIfAnimated = false;
      }
    } catch (error) {
     logger(error);
    }
    return true;
  }
Example #27
Source File: dxc-date-input.component.ts    From halstack-angular with Apache License 2.0 6 votes vote down vote up
@HostListener("document:click", ["$event"])
  public onClickOutsideHandler(event) {
    this.removeRippleCalendarControls();
    if (
      event.target.offsetParent &&
      event.target.offsetParent?.getAttribute("class")
    ) {
      if (
        !event.target.offsetParent
          .getAttribute("class")
          .includes("mde-popover-panel") &&
        !event.target.offsetParent
          .getAttribute("class")
          .includes("mat-calendar-period") &&
        !event.target.offsetParent
          .getAttribute("class")
          .includes("mat-calendar-table")
      ) {
        this.checkOpenCalendar();
      }
    } else {
      this.checkOpenCalendar();
    }
  }
Example #28
Source File: toolbar-color-selector.component.ts    From img-labeler with MIT License 6 votes vote down vote up
@HostListener('document:keyup', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
    const KeyMap = ['KeyR', 'KeyL', 'KeyU', 'KeyM', 'KeyC'];
    if (KeyMap.includes(event.code)) {
      const index = KeyMap.findIndex(e => e === event.code);
      if (this.compactDropDownMenu) {
        const name = environment.colors[index].name;
        if (name !== this.ntype.name) {
          this.setColor(this.colors.findIndex(e => e.name === name));
        }
      } else {
        this.setColor(index);
      }
    }
  }
Example #29
Source File: block.component.ts    From EXOS-Core with MIT License 6 votes vote down vote up
@HostListener('window:keyup', ['$event'])
    keyEvent(event: KeyboardEvent) {
        // tslint:disable-next-line: deprecation
        if (event.keyCode === PAGE_UP) {
            this.increment();
        }

        // tslint:disable-next-line: deprecation
        if (event.keyCode === PAGE_DOWN) {
            this.decrement();
        }

        // tslint:disable-next-line: deprecation
        if (event.keyCode === END) {
            this.openLatest();
        }

        // tslint:disable-next-line: deprecation
        if (event.keyCode === HOME) {
            this.open(0);
        }
    }