Angular 5 - On mouse enter show a button and on mo

2020-08-12 13:41发布

问题:

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.

回答1:

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.