简体   繁体   English

当用户按下 Enter 并且元素失去焦点时触发的事件

[英]Event fired when user presses enter and element loses focus

I want to open a modal whenever the user presses enter on the contenteditable field, and also when the user loses focus on the element.我想在用户在 contenteditable 字段上按下 Enter 时打开一个模式,以及当用户失去对元素的关注时。 The issue is that when the user presses enter, both events are fired (so two modals open up).问题在于,当用户按下 Enter 键时,两个事件都会被触发(因此会打开两个模态)。 How can I find a comfortable compromise, which only allows each of the events to be fired?我怎样才能找到一个舒适的妥协,它只允许触发每个事件?

Code below:代码如下:

HTML HTML

<div (blur)="removeLineBreaks($event); openRenameWebsiteModal($event);"
             (keydown.enter)="openRenameWebsiteModal($event)"
             [attr.contenteditable]="true"
             [attr.spellcheck]="false"
             *ngIf="websiteLoaded"
             id="builder-header-website-name"
             blockNonAlphanumericCharacters
             class="website-name" ngbPopover="Website Name" triggers="mouseenter:mouseleave">{{ websiteName }}</div>

Typescript打字稿

  removeLineBreaks(event: any) {
    event.preventDefault();
    event.stopPropagation();
    BuilderService.removeLineBreaks(event);
  }

  openRenameWebsiteModal(event: any) {
    event.preventDefault();
    event.stopPropagation();
    if (this.websiteName !== event.target.innerHTML) {
      const modal = this.modalService.open(BuilderRenameWebsiteModalComponent, {
        windowClass: 'modal-holder',
        centered: true
      });
      modal.componentInstance.websiteName = this.websiteName;
      modal.componentInstance.newWebsiteName = event.target.innerHTML;
    }
  }

You can easily keep a global variable which checks if the modal is currently open or not.您可以轻松保留一个全局变量,用于检查模式当前是否打开。

modal_open = false;
  openRenameWebsiteModal(event: any) {
    event.preventDefault();
    event.stopPropagation();
    if (this.websiteName !== event.target.innerHTML && !modal_open) {
modal_open = true;
      const modal = this.modalService.open(BuilderRenameWebsiteModalComponent, {
        windowClass: 'modal-holder',
        centered: true
      });
      modal.componentInstance.websiteName = this.websiteName;
      modal.componentInstance.newWebsiteName = event.target.innerHTML;
    }
  }

And if this does not work in some cases, You can use Observables如果这在某些情况下不起作用,您可以使用Observables

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM