我有一个Angular材质表,每个表格行在点击
时会展开在最后一个单元格中,我使用ComponentFactory
动态加载组件,加载的组件是下拉列表。
我遇到的问题是,当点击下拉列表时,表格行会展开和收缩。
这是我向行添加功能的方法
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;let index=index" (click)="expandRow(index, row)" #myRow></mat-row>
这是加载用户侧菜单的单元格:
<ng-container *ngIf="column === 'viewSelection'">
<ng-container matColumnDef="viewSelection">
<mat-header-cell *matHeaderCellDef></mat-header-cell>
<mat-cell *matCellDef="let row">
<ng-container #sideMenu></ng-container>
<!-- <user-side-menu></user-side-menu> -->
</mat-cell>
</ng-container>
</ng-container>
如何加载用户菜单,工作正常:
let sideMenu = this.sideMenu.toArray()
for (let i = 0; i < sideMenu.length; i++) {
const factory = this.resolver.resolveComponentFactory(this.ellipsis);
let container = this.sideMenu.toArray()[i]
const ellipsisComponent = container.createComponent(factory);
ellipsisComponent.instance.data = this.returnedData[i]
console.log(container, ellipsisComponent.data);
加载用户菜单的Html:
<a aria-expanded="false" aria-haspopup="true" class="btn btn-icon has-dropdown" data-toggle="dropdown" id="grid-menu">
<i class="ion-more"></i>
</a>
<div class="c-dropdown__menu dropdown-menu" aria-labelledby="grid-menu">
<a class="c-dropdown__item dropdown-item" (click)="viewUser({Id:data?.Id}, $event); $event.preventDefault()" >View/Edit User</a>
<a *ngIf="data?.IsActive" class="c-dropdown__item dropdown-item" (click)="activeDeactivateUser(data?.Id, false); $event.preventDefault()" data-toggle="modal" data-target="#deactivate-member">Deactivate User</a>
<a *ngIf="!data?.IsActive" class="c-dropdown__item dropdown-item" (click)="activeDeactivateUser(data?.Id, true); $event.preventDefault()" data-toggle="modal" data-target="#activate-member">Activate User</a>
</div>
正如你所看到我使用防止默认,这没有做任何事,尝试过 停止传播但这会停止我想要执行的函数
希望有人能指出我正确的方向
答案 0 :(得分:1)
您需要使用stopPropagation()
来阻止事件传递给父DOM。您使用preventDefault()
来停止对事件对象采取默认事件操作。例如,对于锚元素,默认单击操作是打开链接,因此如果要实施特殊检查以防止在特定条件下打开链接,可以使用preventDefault()
从(click)
回调函数中做到这一点。但是如果你想阻止click事件传递给父元素,你可以使用stopPropagation()
:
<span onclick="alert('You've already visited Stack Overflow')">
<a href="https://stackoverflow.com" (click)="visitStack($event)">
Stack Overflow
</a>
</span>
stackVisited = false;
visitStack(event) {
if (this.stackVisited) {
event.preventDefault();
} else {
this.stackVisited = true;
event.stopPropagation();
}
}