【问题标题】:How to do event bubbling in Angular?如何在 Angular 中进行事件冒泡?
【发布时间】:2019-08-12 14:43:34
【问题描述】:

在这个stackblitz example

当我点击红色按钮时,我应该只在控制台中看到红色而不是灰色。 我怎样才能做到这一点?

    import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
<button style="height: 100px; width: 200px;" (click)='gray()'> Gray
<button style="height: 20px; width: 40px; background-color:red" (click)='red()'>
Red
</button>
</button>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  red() {
    console.log('red');
  }

  gray() {
    console.log('gray');
  }
}

编辑:我已将问题调整为 div 内的按钮

【问题讨论】:

  • 无论框架如何,将
  • 我可以想象一个屏幕阅读器会找出按钮的作用。仅仅因为它有效并不意味着你应该这样做。

标签: angular


【解决方案1】:

我在下面更新了您的代码。当您单击红色按钮时,您要传递单击事件(显示为$event),然后使用此事件,在您调用的方法中,添加event.stopPropogation(); 以停止触发下一个鼠标事件。

import { Component, Input } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
<button style="height: 100px; width: 200px;" (click)='gray()'> Gray
<button style="height: 20px; width: 40px; background-color:red" (click)='red($event)'>
Red
</button>
</button>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  red($event: MouseEvent) {
    console.log('red');
    $event.stopPropagation();
  }

  gray() {
    console.log('gray');
  }
}

PS。最终你不应该嵌套按钮。

【讨论】:

  • 您没有在 HTML 的 red() 方法中添加 $event 参数。应该是(click)='red($event)'
猜你喜欢
  • 2020-05-16
  • 2011-01-23
  • 1970-01-01
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多