How to not apply [routerLink] on a child element?

大城市里の小女人 提交于 2019-12-10 20:28:02

问题


I want to make a child element to trigger it own click even , and don't respond to it parent element having [routerLink], the problem is the child element can't run it delete() function in (click)="delete()" it just follow it parent in [routerLink] (it navigate to /product/:id)

    <div class="item">

<!-- parent element -->
    <a [routerLink]="['/product/'+product.id]">
        <div class="figure">
          <div class="sides">
            <div class="side">
              <div class="card">
<img class="img" [src]="product.thumb"> 
                <div class="content">
                  <div class="header">{{product.name}}</div>
                  <div class="meta"> <span>product.category</span> </div>
                </div>
                <div class="extraContent"> <span class="ui right floated black">

                <!-- child element -->
                <a (click)="delete()" ><i class="red trash outline icon"></i></a></span> <span><i class="deleteProductIcon"></i></span> </div> 
                <!-- child element -->

              </div>
            </div>
          </div>
        </div>
      </a>
<!-- parent element -->

</div>

I tried to move [routerLink] to an upper div but it still doing the same behavior


回答1:


if you stopPropgation in the delete function() the event won't bubble up to the anchor tag with the routerLink

// pass in the event object to the delete function
<a (click)="delete($event)" ><i class="red trash outline icon"></i></a>

// in the delete function, stop event propagation
delete(event){
    event.stopPropagation();
}



回答2:


In your case the child just specifying stopPropagation might not work sometimes. Specially when child and parent both have their separate "routerLinks" defined

I suggest handling the routing using "navigate" method in component and returning "false" in the end. This would prevent parent route to trigger after completion of click handler of child.

// pass in the event object to the delete function
<a (click)="delete($event)" ><i class="red trash outline icon"></i></a>

// in the delete function, stop event propagation
delete(event){
    event.stopPropagation();
    this.route.navigate(['child/route/here']);
    return false;
}

returning false from click handler prevented the parent route to work for me.




回答3:


the event.stopPropagation(); only, did not work for me. All I had to do was drop in e.preventDefault(); too

// In your HTML   
<a [routerLink]="['/product/'+product.id]">
     <!-- your other inner stuff -->
     <a (click)="delete($event)" ><i class="red trash outline icon"></i></a>
</a>

// In your component
delete(e){
    e.stopPropagation();
    e.preventDefault();
}


来源:https://stackoverflow.com/questions/44726816/how-to-not-apply-routerlink-on-a-child-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!