在Angular中停止鼠标事件传播的最简单方法是什么?

我应该传递特殊的$event对象和调用stopPropagation()自己或有一些其他的方式。

例如,在Meteor中,我可以简单地从事件处理程序返回false。


当前回答

补充来自@AndroidUniversity的答案。在单行中你可以这样写:

<component (click)="$event.stopPropagation()"></component>

其他回答

补充来自@AndroidUniversity的答案。在单行中你可以这样写:

<component (click)="$event.stopPropagation()"></component>

我不得不stopPropagation和preventDefault,以防止按钮展开上面的手风琴项。

所以…

@Component({
  template: `
    <button (click)="doSomething($event); false">Test</button>
  `
})
export class MyComponent {
  doSomething(e) {
    e.stopPropagation();
    // do other stuff...
  }
}

我使用

<... (click)="..;..; ..someOtherFunctions(mybesomevalue); $event.stopPropagation();" ...>...

简而言之,只需用';'分隔其他事物/函数调用,并添加$event.stopPropagation()

提供的大多数解决方案都适用于Angular 11以上的版本,对于Angular 11或以下版本,我找到了一个可以使用的变通方案:

export class UiButtonComponent implements OnInit, OnDestroy {

  @Input() disabled = false;

  clickEmitter: Subject<any> = new Subject();

  constructor(private elementRef: ElementRef) { }

  ngOnInit(): void {
    this.elementRef.nativeElement.eventListeners()
      .map(listener => this.clickEmitter.pipe(filter(event => Boolean(event))).subscribe(event => listener(event)));
    this.elementRef.nativeElement.removeAllListeners();
    this.elementRef.nativeElement.addEventListener('click', (event) => {
      if (!this.disabled) {
        this.clickEmitter.next(event);
      }
    });
  }

  ngOnDestroy(): void {
    this.clickEmitter.complete();
  }
}

我基本上把当前组件的每个侦听器都放在Observable上,然后,我只注册一个侦听器,并在那里管理操作。

上面的例子是在给定一个布尔变量的情况下禁用按钮上的click事件。

这招对我很管用:

mycomponent.component.ts:

action(event): void {
  event.stopPropagation();
}

mycomponent.component.html:

<button mat-icon-button (click)="action($event);false">Click me !<button/>