如何使整个 Angular 组件可点击
How to make the entire Angular component clickable
我有以下模板:
<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-selector
是MyComponent
组件的选择器,有如下模板:
<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>
如您所见,单击项目描述会将我重定向到详细信息,但我希望整个组件都可以单击,而不仅仅是文本。
我怎样才能做到这一点?
你可以在组件上使用点击事件,当你点击组件时它会调用动作
<my-component-selector class="myItem" [item]="item" (click)="DoSth($event)"></my-component-selector>
如果你想在模板中处理点击。在模板中放一个 <div>
并在那里添加点击事件
如果您将按钮移到 a
标签内并设置其样式以采用完整的可用宽度和高度,您应该能够得到您想要的:
我的组件模板:
<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%;
}
我创建了一个 quick'n'dirty Stackblitz。
我有以下模板:
<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-selector
是MyComponent
组件的选择器,有如下模板:
<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>
如您所见,单击项目描述会将我重定向到详细信息,但我希望整个组件都可以单击,而不仅仅是文本。 我怎样才能做到这一点?
你可以在组件上使用点击事件,当你点击组件时它会调用动作
<my-component-selector class="myItem" [item]="item" (click)="DoSth($event)"></my-component-selector>
如果你想在模板中处理点击。在模板中放一个 <div>
并在那里添加点击事件
如果您将按钮移到 a
标签内并设置其样式以采用完整的可用宽度和高度,您应该能够得到您想要的:
我的组件模板:
<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%;
}
我创建了一个 quick'n'dirty Stackblitz。