我在div内有一个文本输入。 单击输入应将其设置为焦点并停止div 单击事件的冒泡。我已经尝试了文本输入事件的stopPropagation
和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;
}
您有两个不同的事件,一个是mousedown
,另一个是click
。
e.stopPropagation(( 仅在两个事件属于同一类型时才有效。
您可以像这样更改输入以按预期工作:
<input #inputBox matInput (click)="fireEvent($event)" max-width="12" />
现场示例:https://stackblitz.com/edit/angular-material-basic-stack-55598740?file=app/input-overview-example.ts
您只能停止同一事件的传播。
fireEvent
函数会停止传播 mousedown
事件,但不会停止传播click
事件。
如果要停止传播以单击,请尝试在输入上添加另一个单击事件并从那里停止传播
例如
<input #inputBox matInput (click)="$event.stopPropagation()" max-width="12" />
你的其他功能只需要知道需要什么,即设置焦点
fireEvent(e) {
this.inputBox.nativeElement.focus();
console.log('click inside input');
}
preventDefault()
防止默认行为,它与冒泡或事件无关,因此您可以安全地忽略它
尝试使用 (click)="$event.stopPropagation()"
.它可能会有所帮助,因为它在我的场景中对我有用。