简体   繁体   English

Angular 2 防止子组件点击路由器导航

[英]Angular 2 prevent router navigation on child component click

I have a template我有一个模板

<div (click)="handler()">
  <input type='checkbox' (click)="$event.stopPropagation()" (change)="$event.stopPropagation()">
</div>

and in my component here is the handler在我的组件中,这里是处理程序

handler() {
  this.router.navigate('path');
}

I wanted do nothing on checkbox click but to route on div click.我想在复选框单击时什么也不做,而是在 div 单击时路由。

The above solution is not working.上述解决方案不起作用。

First argument of navigate function has to be an array导航 function 的第一个参数必须是一个数组

this.router.navigate(['path']);

OR或者

you can use navigateByUrl ,您可以使用navigateByUrl

this.router.navigateByUrl('path');

Since you are using $event.stopPropagation() when you click on the checkbox, navigation won't happen but when you simply click on the div, you will be navigated to expected route.由于您在单击复选框时使用$event.stopPropagation() ,因此不会发生导航,但是当您只需单击 div 时,您将被导航到预期的路线。

This setup works for me:此设置对我有用:

<div (click)="onDivClick()">
  <mat-checkbox (click)="$event.stopPropagation()" (change)="onCheckboxChange($event)"></mat-checkbox>
</div>

...

onDivClick() {
  console.log('div clicked');
}

onCheckboxChange(event) {
  console.log(event);
}

Important to note:需要注意的重要事项:
MatCheckboxChange event type does not have a stopPropagation() function so your example code should actually display an error in the console. MatCheckboxChange事件类型没有stopPropagation() function 因此您的示例代码实际上应该在控制台中显示错误。
So you want the stopPropagation() only on the checkbox click.因此,您只希望在单击复选框时使用stopPropagation()

I figured out I have a label that wraps the checkbox.我发现我有一个包装复选框的 label。 So, I needed to add the click event to stop propagation at the label element因此,我需要在 label 元素处添加点击事件以停止传播

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 6 Router导航未在目标组件中呈现子组件 - Angular 6 Router navigation not rendering child component in the destination component 当我点击 angular 中 app.component 中的导航栏时,到达我的路由器插座的 div - Reach the div of my router-outlet when I click on the navigation bar in the app.component in angular 在同一导航单击时重新加载路由器组件 - 在导航单击时刷新页面 - reload router component on same navigation click - refresh page on nav click 角路由器如何从父组件调用子组件 - angular router how to call child component from the parent component 在 router.navigate 之后防止 Angular 组件渲染 - Prevent Angular component rendering after router.navigate Angular 2/4/5 - 将子组件加载到主路由器插座 - Angular 2/4/5 - Load child component to main router-outlet 角度UI路由器-组件-父级-子级-嵌套-视图未加载 - Angular UI-Router - Component - Parent - Child - Nested - View not load Angular路由器从根组件获取子参数 - Angular router get child param from root component React - 如何防止来自子组件的点击事件 - React - How to prevent click event from child component Angular Parent / Children单击事件:在父组件中的其他子项上单击事件后,在父项中显示子组件? - Angular Parent/Children click events: Show child component in parent after click event on a different child in parent component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM