use*_*042 7 javascript event-bubbling typescript3.0 angular7
我在div中输入了文本。单击输入应将其设置为焦点并停止div click事件的冒泡。我尝试了stopPropagationand preventDefault在文本输入事件上,但无济于事。控制台日志显示div单击仍然执行。如何停止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;
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*iro 22
你有两个不同的事件,一个是mousedown,另一个是click。
e.stopPropagation() 仅在两个事件类型相同时才有效。
您可以像这样更改输入以按预期工作:
<input #inputBox matInput (click)="fireEvent($event)" max-width="12" />
Run Code Online (Sandbox Code Playgroud)
现场示例: https : //stackblitz.com/edit/angular-material-basic-stack-55598740?file=app/input-overview-example.ts
Gon*_*o.- 12
您只能停止同一事件的传播。
您的fireEvent函数会停止为您的mousedown事件传播,但不会为您的click事件停止传播。
如果要停止传播以单击,请尝试在输入上添加另一个单击事件并从那里停止传播
例如
<input #inputBox matInput (click)="$event.stopPropagation()" max-width="12" />
Run Code Online (Sandbox Code Playgroud)
你的其他功能只需要知道需要什么,即设置焦点
fireEvent(e) {
this.inputBox.nativeElement.focus();
console.log('click inside input');
}
Run Code Online (Sandbox Code Playgroud)
preventDefault() 防止默认行为,它与冒泡或事件无关,因此您可以安全地忽略它