简体   繁体   English

双击 Angular 指令

[英]Double click Angular directive

I have the following template in Angular 7:我在 Angular 7 中有以下模板:

<ul class="posts">
  <li *ngFor="let post of posts">
    <h2>{{post.title}}</h2>
    <a (click)="delete(post)">Delete Post</a>
  </li>
</ul>

I would like to create a confirm directive to be used as:我想创建一个确认指令用作:

<a (click)="delete(post)" confirm="Confirm delete" class="delete">Delete Post</a>

The moment is clicked (one is enough) it changes to:单击的那一刻(一个就足够了)它变为:

<a (click)="delete(post)" confirm="Confirm delete" class="delete confirm">Confirm delete</a>

So what happens is:那么会发生什么:
- Anchor's text changes from "Delete Post" to the one inside confirm, eg "Confirm Delete"; - 锚文本从“删除帖子”变为里面的确认,例如“确认删除”;
- Class "confirm" is added to anchor CSS classes; - 锚CSS类中添加了“confirm”类;
- Delete(post) method is only called after anchor being clicked on "confirm mode"; - 只有在“确认模式”点击锚点后才会调用Delete(post)方法;
- After being clicked on "confirm mode" OR 5 seconds go by without being clicked it goes to its original state: - 点击“确认模式”或 5 秒后没有被点击,它会进入原始状态:

<a (click)="delete(post)" confirm="Confirm delete" class="delete">Delete Post</a>

Can this be done with a directive?这可以通过指令完成吗?

import { Directive } from '@angular/core';

@Directive({
  selector: '[confirm]'
})

export class ConfirmDirective {

  constructor(el: ElementRef) {
     el.nativeElement ...
  }

}

I started to create the directive but I am really not sure how to do this.我开始创建指令,但我真的不知道如何做到这一点。

Update:更新:

If you really want to, you actually can do it with a directive.如果你真的想要,你实际上可以用指令来做。 Try this:尝试这个:

import { Directive, ElementRef, Input, Renderer2, OnInit } from '@angular/core';
import { Observable, Subject, BehaviorSubject, timer, fromEvent } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Directive({
  selector: '[confirm]'
})
export class ConfirmDirective implements OnInit {
  @Input('confirm') delete: Function;
  private confirm$ = fromEvent(this.el.nativeElement, 'click');
  private confirmTimeout: number = 5000;
  private timer$: Observable<number>;
  private isConfirming = new BehaviorSubject<boolean>(false);
  private isConfirming$ = this.isConfirming.asObservable();

  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngOnInit() {
    this.isConfirming$.subscribe((isConfirming) => this.setLabel(isConfirming));
    this.confirm$.subscribe((event: any) => this.doConfirm());
  }

  setLabel(isConfirming: boolean): void {
    // set the correct element text and styles
    let text: any;
    let textEl = this.renderer.createElement('span');

    if (this.el.nativeElement.firstChild) {
      this.renderer.removeChild(this.el.nativeElement, this.el.nativeElement.firstChild);
    }
    if (this.isConfirming.value) { // we are confirming right now
      text = this.renderer.createText('Please confirm delete');
      this.renderer.addClass(this.el.nativeElement, 'delete');
    } else {
      text = this.renderer.createText('Delete');
      this.renderer.removeClass(this.el.nativeElement, 'delete');
    }

    this.renderer.appendChild(this.el.nativeElement, text);
  }

  doConfirm(): void {
    if (this.isConfirming.value === false) { // start confirming
      this.timer$ = timer(this.confirmTimeout);
      this.isConfirming.next(true);

      // start the timer
      this.timer$
          .pipe(
            takeUntil(this.confirm$) // stop timer when confirm$ emits (this happens when the button is clicked again)
          )
            .subscribe(() => {
            this.isConfirming.next(false); // timeout done - confirm cancelled
        });
    } else { // delete confirmation
      this.isConfirming.next(false);
      this.delete(); // this is the delete action that was passed to the directive
    }
  }
}

You would apply it to an element like this, passing in the actual delete method as a parameter.您可以将它应用于这样的元素,将实际的delete方法作为参数传递。

<button type="button" [confirm]="delete"></button>

Working example: https://stackblitz.com/edit/angular-wdfcux工作示例: https : //stackblitz.com/edit/angular-wdfcux

Old answer:旧答案:

Not sure a directive would be the best way to go.不确定指令是最好的方法。 It could probably be done but you'd have to intercept the click handler somehow and/or pass the delete method to it.它可能可以完成,但您必须以某种方式拦截点击处理程序和/或将删除方法传递给它。 It would probably be messy.估计会很乱。

I'd probably create a component for the delete button and handle it there (well actually that's a lie, if this were me I'd use the native confirm dialog and be done with it, but you don't want to).我可能会为删除按钮创建一个组件并在那里处理它(实际上这是一个谎言,如果是我,我会使用本机confirm对话框并完成它,但您不想这样做)。

Something like this:像这样的东西:

import { Component } from '@angular/core';
import { Observable, Subject, timer } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'delete-button',
  template: `<button type="button" (click)="delete()" [ngClass]="{ delete: isConfirming }">{{ label }}</button>`,
  styles: ['.delete { background-color: teal; color: white; } ']
})
export class DeleteButtonComponent {
  private confirmTimeout: number = 5000;
  private timer$: Observable<number>;
  private cancelTimer = new Subject();
  public isConfirming: boolean = false;

  constructor() {}

  get label(): string {
    return this.isConfirming
      ? 'Please confirm delete'
      : 'Delete'
  }

  delete() {
    if (!this.isConfirming) {
      this.timer$ = timer(this.confirmTimeout);
      this.isConfirming = true;

      this.timer$
          .pipe(
            takeUntil(this.cancelTimer)
          ).subscribe(() => {
            this.isConfirming = false;
        }, null, () => this.isConfirming = false);
    } else {
      this.cancelTimer.next();
      // really delete
    }
  }
}

Working example: https://stackblitz.com/edit/angular-z6fek4工作示例: https : //stackblitz.com/edit/angular-z6fek4

You can use rxjs takeUntil,你可以使用 rxjs takeUntil,

posts: any[] = [
  { id: 1, title: 'post 1', deleteText: 'Delete Post' },
  { id: 2, title: 'post 2', deleteText: 'Delete Post' }
];

delete(post) {
  post.deleteText = 'Click to Confirm';
  post.css = 'custom';
  let confirm$ = fromEvent(document.getElementById('post-' + post.id), 'click');
  let timer$ = timer(5000)

  confirm$
    .pipe(
      takeUntil(timer$)
    )
    .subscribe(() => {
      console.log('ready to delete');
      this.posts = this.posts.filter(p => p.id !== post.id);
    });



  timer$
    .subscribe(() => {
      if (this.posts.find(p => p.id === post.id)) {
        console.log('timer is up, abort delete');
        post.deleteText = 'Delete Post';
        post.css = '';
      }
    });
  }

HtML: html:

<ul class="posts">
   <li *ngFor="let post of posts">
      <h2>{{post.title}}</h2>
      <a (click)="delete(post)" [ngClass]="post.css" [id]="'post-'+post.id">          {{post.deleteText}}</a>
  </li>
</ul>

demo: https://stackblitz.com/edit/angular-7-master-xg8phb演示: https : //stackblitz.com/edit/angular-7-master-xg8phb

(also need to manage subscriptions) (还需要管理订阅)

You can add host element behavior bindings and listeners through a directive with @HostBinding and @HostListener , as well as arbitrary @Input s bound to the directive itself:您可以通过带有@HostBinding@HostListener的指令以及绑定到指令本身的任意@Input来添加宿主元素行为绑定和侦听器:

@Directive({
  selector: '[confirm]'
})

export class ConfirmDirective {

  @HostListener('dblclick') onDoubleClick(event) {
    // .. do double click logic, just like binding (dbclick) to an element
  }

  @HostBinding('class.confirm') confirmStyle: boolean; // toggles class on host, just like with template binding

  @Input('confirm') confirm: boolean; // State from outside the directive that can be bound to the directive attribute directly, i.e. 'click to confirm' box

  constructor(el: ElementRef) {
     el.nativeElement ...
  }

}

If you're looking to directly add HTML / markup with the directive for a confirm button, this behavior is instead better wrapped with a component instead.如果您希望使用确认按钮的指令直接添加 HTML/标记,则最好将此行为与组件一起包装。 Components are for views;组件用于视图; directives are for behavior.指令是针对行为的。 One idea is to wrap the confirm dialog(?) into a service that the directive can call.一种想法是将确认对话框(?)包装到指令可以调用的服务中。

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

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