【问题标题】:How to make the entire Angular component clickable如何使整个 Angular 组件可点击
【发布时间】:2019-08-10 23:14:06
【问题描述】:

我有以下模板:

<mat-nav-list class="myList">
    <a mat-list-item *ngFor="let item of items">
        <my-component-selector class="myItem" [item]="item"></my-component-selector>
    </a>
</mat-nav-list>

my-component-selectorMyComponent组件的选择器,模板如下:

<a class="item-description" routerLink="/details/{{item.getId()}}">{{item.getDescription()}}</a>
<button mat-icon-button (click)="deleteItem(); $event.stopPropagation();"><mat-icon>delete</mat-icon></button>

如您所见,单击项目描述会将我重定向到详细信息,但我希望整个组件都可单击,而不仅仅是文本。 我怎样才能做到这一点?

【问题讨论】:

    标签: angular angular7 angular-components


    【解决方案1】:

    如果您将按钮移动到a-tag 内并设置其样式以获取完整的可用宽度和高度,您应该能够得到您想要的:

    我的组件模板:

    <a class="item-description" routerLink="/details/{{item.getId()}}">
      {{item.getDescription()}}
      <button mat-icon-button (click)="deleteItem(); $event.stopPropagation();"><mat-icon>delete</mat-icon></button>
    </a>
    

    我的组件 CSS

    ::ng-deep my-component-selector{
        display:flex; 
        flex-grow:1;
    }
    a{
      display:inline-block;
      width:100%;
    }
    

    我创建了一个快速的'n'dirty Stackblitz

    【讨论】:

      【解决方案2】:

      如果您想处理模板中的点击。在模板中放一个&lt;div&gt;,并在那里添加点击事件

      【讨论】:

        【解决方案3】:

        您可以在组件上使用点击事件,一旦您点击该组件就会调用该操作

         <my-component-selector class="myItem" [item]="item" (click)="DoSth($event)"></my-component-selector>
        

        【讨论】:

        • 是的,但我希望MyComponent 负责处理点击,您的解决方案建议我处理其他组件模板内部的点击。
        • 您应该处理包含您的组件(我的组件选择器)的组件内部的点击让我们假设您在主模板中显示此组件,因此您应该处理主组件 ts 文件中的操作
        猜你喜欢
        • 2021-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 2018-08-07
        • 1970-01-01
        • 2015-06-16
        相关资源
        最近更新 更多