Source:  Twitter logo

When a user hovers over a list item i want a button to be displayed. When the user leaves the list item i want the button to not be displayed.

I have come across a mouseenter event and a 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");
}

Apart from declaring these functions, i dont know how to target the button within this list item to show and hide it depending on if the user has entered the list-item block or left.

I have created a solution for this.

When a user "mouseenters" the mat-item-list block i set a variable to true and add a ng-if in the button so when the variable is true it shows and when the user "mouseleaves" from the mat-item-list the variable is set to false. This works fine assuming you only have a single mat-item-list.

Having multiple means i need a variable to store an index value when the user enters the block and i determine if the index value set is the same one as im hovering over. If it is the button will be shown.

.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;
}

This solution seems more cleaner than trying to find a specific dom element and adding a display:block/none to it.

22 users liked answer #0dislike answer #022
Kay profile pic
Kay

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).