javascript - Typescript 3 Angular 7 StopPropagation 和 PreventDefault 不起作用
问题描述
我在 div 中有一个文本输入。单击输入应将其设置为焦点并停止 div 单击事件的冒泡。我已经在文本输入事件上尝试了stopPropagation
and preventDefault
,但无济于事。控制台日志显示 div click 仍然执行。如何停止执行 div 点击事件?
// html
<div (click)="divClick()" >
<mat-card mat-ripple>
<mat-card-header>
<mat-card-title>
<div style="width: 100px">
<input #inputBox matInput (mousedown)="fireEvent($event)" max-width="12" />
</div>
</mat-card-title>
</mat-card-header>
</mat-card>
</div>
// component
@ViewChild('inputBox') inputBox: ElementRef;
divClick() {
console.log('click inside div');
}
fireEvent(e) {
this.inputBox.nativeElement.focus();
e.stopPropagation();
e.preventDefault();
console.log('click inside input');
return false;
}
解决方案
你有两个不同的事件,一个是mousedown
,另一个是click
。
e.stopPropagation() 仅在两个事件属于同一类型时才有效。
您可以像这样更改输入以按预期工作:
<input #inputBox matInput (click)="fireEvent($event)" max-width="12" />
推荐阅读
- angular - Angular:可观察服务不从 api 获取数据
- python - 努力消除异常值
- javascript - 在相对于页面的固定 div 内滚动内容
- javascript - 用户停止输入后处理更新的最佳方式是什么?
- c - 从 ELF 文件生成全上下文符号表
- python - 什么时候将新的 tensorflow 版本上传到 piwheels.org?
- amazon-web-services - AWS - ECS - 如何在现有 ECS(带有 1 个 EC2)实例上重新部署更新的 Docker 映像?
- python - 将 Jquery 库链接到 Django 扩展模板的问题
- python - 是否可以使用 yacc 打印 (x AND ( y OR z)) 之类的表达式的所有可能性?
- python - 在没有 Visual Studio 许可的情况下为 Windows 编译 CPython 3.x 扩展模块