【问题标题】:Override routerLink on Button Click在按钮单击时覆盖 routerLink
【发布时间】:2016-12-03 21:44:24
【问题描述】:

我正在制作一个电子商务网站,我的目标是每个对象有多个输入点,例如,他们点击/点击卡片上除按钮之外的任何位置,点击/点击时会转到产品详细信息/点击按钮将该项目添加到购物车。

目前我将其转发到详细信息没有问题,即使点击按钮也会转发到详细信息。我想让按钮的操作覆盖路由器。

这是我目前的尝试:

<a *ngFor="let item of list"  >
<div class="col-lg-3 col-md-4 col-xs-6">
    <div class="card" [routerLink]="['/detail', item.item_number]">
    <img style ="width:170px;height:150px; display:block;"alt="170x150" src="{{item.item_image}}">

    <div class="card-block">
    <p class="card-text text-muted">{{item.item_name}}</p>
    <p class="card-text">Size:{{item.item_length}}</p>
    </div>

    <div class="container">        
    <button type="button" class="btn btn-primary btn-block" (click)="addItem()">Add<span [routerLink]="['/detail', item.item_number]" [class.disabled]="disabled ? true : null"></span></button>
    </div>
</div>
</div>
</a>

我希望在按钮中嵌套禁用命令会起作用,但似乎并非如此。任何想法都会很棒!

【问题讨论】:

    标签: angular angular2-routing angular2-template


    【解决方案1】:

    在按钮的点击事件中添加stopPropagation() 应该可以解决问题:

    <button type="button" class="btn btn-primary btn-block" 
    (click)="addItem();$event.stopPropagation()">Add<span [routerLink]="['/detail', item.item_number]" 
    [class.disabled]="disabled ? true : null"></span></button>
    

    这可以防止当前事件在捕获和冒泡阶段进一步传播。阅读更多关于stopPropagation()here的信息。

    【讨论】:

    • 喂,真不敢相信我没有想到 $event.stopPropagation。谢谢您的帮助。我最终删除了跨度,因为我只需要 stopProp。
    【解决方案2】:

    我希望我的所有 Post DIV 都链接到 Post-Detail 页面,但我也有一个滑块(想想 Instagram 之类的带有箭头的东西,用户也可以用手指滑动它)所以我的解决方案是将整个 div 放入带有 routerLink 的标签中,并将滑块放入带有 href="javascript:void(0);" 的标签中和 (click)="$event.stopPropagation()" 组件Html代码是这样的:

    <a [routerLink]="['/profile','feed-detail',postItem.uniqueCode]">
       <div class="content-wrap" [ngClass]="{'is-hidden': showComments}">
           ...
            <a href="javascript:void(0);" (click)="$event.stopPropagation()">
                <app-carousel>
                    ...
                <app-carousel>
            </a><!-- closing the javascript:void(0) a tag-->
       </div> <!-- closing the content-wrap div-->
    </a> <!-- closing the routerLink a tag-->
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 1970-01-01
      • 2015-07-30
      • 2023-02-23
      • 2014-12-02
      相关资源
      最近更新 更多