Angular 5 - 鼠标进入显示按钮,鼠标离开隐藏按钮

15
当用户将鼠标悬停在列表项上时,我希望显示一个按钮。当用户离开列表项时,我希望该按钮不再显示。
我发现了一个mouseenter事件和一个mouseleave事件。 .html
<mat-list-item (mouseenter)="enter($event)" (mouseleave)="leave($event)" class="chat-message-body" *ngIf="auth._id !== message.author._id" fxLayoutAlign=""
    dir="ltl">
    <div matLine>
        <b>{{message.author.profile.username}} </b>
        <span>{{message.created_at | date:'shortTime'}} </span>
    </div>
    <button mat-icon-button>
        <mat-icon aria-label="">keyboard_arrow_down</mat-icon>
    </button>
    <span matLine> {{message.body}} </span>
    <img matListAvatar class="img-box" src="http://via.placeholder.com/30x30" alt="...">
</mat-list-item>

.ts

enter(e) {
    console.log("enter");
}

leave(e) {
    console.log("leave");
}

除了声明这些函数,我不知道如何针对列表项中的按钮进行定位,以便根据用户是否进入了列表项块或离开来显示和隐藏它。

enter image description here


此块是否在 ngFor 中?这听起来有歧义。 - Armen Vardanyan
是的,它在ngFor中。 - Kay
你能为这个创建一个 stackblitz.com 吗? - cgatian
@cgatian 现在不需要了,我想我解决了。 - Kay
1个回答

22

我已经为此创建了一个解决方案。

当用户“鼠标进入”mat-item-list块时,我将变量设置为true,并在按钮中添加ng-if,因此当变量为true时,它会显示,当用户从mat-item-list“鼠标离开”时,变量设置为false。假设您只有一个mat-item-list,则此方法有效。

如果有多个,则需要一个变量来存储索引值,当用户进入该块时,我确定设置的索引值是否与我正在悬停的值相同。如果是,则会显示该按钮。

.html

<mat-list dense>
        <ng-template ngFor let-message [ngForOf]="conversation?.messages" let-i="index" let-odd="odd" [ngForTrackBy]="trackById">
            <mat-list-item (mouseenter)="enter(i)" (mouseleave)="leave(i)" class="chat-message-body" *ngIf="auth._id === message.author._id"
                fxLayoutAlign="" dir="rtl">
                <img matListAvatar class="img-box" src="http://via.placeholder.com/30x30" alt="...">
                <button mat-icon-button *ngIf="hoverIndex == i">
                    <mat-icon aria-label="">keyboard_arrow_down</mat-icon>
                </button>
                <div matLine>
                    <b>{{message.author.profile.username}} </b>
                    <span>{{message.created_at | date:'shortTime'}} </span>
                </div>
                <span matLine> {{message.body}} </span>
            </mat-list-item>
        </ng-template>
    </mat-list>

.ts

enter(i) {
    this.hoverIndex = i;
}

leave(i) {
    this.hoverIndex = null;
}

这种解决方案似乎比尝试找到特定的DOM元素并向其添加display:block/none更加简洁。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接