How to toggle element visibility when hovering in Angular?

I've set up an angular material card that includes a close button (marked with an "x").

My goal is to initially hide the "x" button and only display it when hovering over the card.


Here is the code snippet for the card:

<mat-card>
    <mat-card-title>hello title</mat-card-title>
    <mat-card-content>hello content</mat-card-content>
    <mat-card-actions>
        <button mat-icon-button><mat-icon>close</mat-icon></button>
    </mat-card-actions>
</mat-card>

I considered using ngClass, but I wasn't sure how to indicate whether the user is currently hovering over the card or not.

Answer №1

Give this a try:

<mat-card (mouseover)="displayButton = true" (mouseleave)="displayButton = false" >
    <mat-card-title>awesome title</mat-card-title>
    <mat-card-content>fantastic content</mat-card-content>
    <mat-card-actions>
        <button mat-icon-button *ngIf = "displayButton"><mat-icon>close</mat-icon></button>
    </mat-card-actions>
</mat-card>

In your component's .ts file, declare the displayButton variable like this:

displayButton: boolean = false;

Answer №2

There are multiple ways to solve this issue

1. One option is to use scss or css

html file

<mat-card class="CARD">
   <mat-card-title>hello title</mat-card-title>
   <mat-card-content>hello content</mat-card-content>
   <mat-card-actions>
    <button class="CLOSE" mat-icon-button><mat-icon>close</mat-icon></button>
   </mat-card-actions>
</mat-card>

.scss file

.CLOSE {
        display : none;
      }
.CARD {
           &:hover {
               .CLOSE {
                display : block !important
              }
            }
         }

2. Another approach is using variables .ts file

 btnVisible: boolean = true;

.html file

<mat-card (mouseover)="btnVisible = false" (mouseleave)="btnVisible = true" >
<mat-card-title>hello title</mat-card-title>
<mat-card-content>hello content</mat-card-content>
<mat-card-actions>
    <button mat-icon-button *ngIf ="btnVisible"><mat-icon>close</mat-icon></button>
</mat-card-actions>

Hopefully, these solutions will be beneficial for everyone!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The existence of useRef.current is conditional upon its scope, and it may be null in certain

I'm currently working on drawing an image on a canvas using React and Fabric.js. Check out the demo here. In the provided demo, when you click the "Draw image" button, you may notice that the image is not immediately drawn on the canvas as expected. ...

Typescript - Creating a Class with Constructor that Extends an Interface without Constructor

I am faced with an interface structured as follows: interface Person { id: number name: string } In my implementation class for this interface, I have the following code: class PersonClass implements Person { id: number = 123 name: string = &apo ...

Angular 6 and above: The use of ProvidedIn in a submodule is leading to a circular dependency issue

A resolve service is being implemented using the new providedIn attribute. This translations resolver is utilized in a protected module: import { Injectable } from '@angular/core'; import { Observable , pipe } from 'rxjs'; import { ...

Switch between div elements in Angular 2 while dynamically changing their values depending on a specific condition for displaying or hiding

After referring to the solution found in (Hide/show individual items inside ngFor), I am facing a challenge regarding setting the value of pinMe[j] based on a condition. In my scenario, I need to toggle between div elements while also determining what shou ...

When working with Expo and React Native in TypeScript, VS code IntelliSense recommends using 'react-native/types' instead of just 'react-native'

My React Native TypeScript setup is showing react-native/types instead of react-native in IntelliSense. How can I fix this issue? I initialized my project using npx create-expo-app MyApp --template Typescript. Here is my tsconfig.json configuration. { ...

Tips for refining TypeScript discriminated unions by using discriminators that are only partially known?

Currently in the process of developing a React hook to abstract state for different features sharing common function arguments, while also having specific feature-related arguments that should be required or disallowed based on the enabled features. The ho ...

What is the datatype for an Angular FormControl when dealing with numbers?

Having an issue with Angular FormControl when using it for text and number inputs. Both inputs are being recorded as text even though one is supposed to be a number. var control = this._formBuilder.control(this.settings[input.property]); control.valueChan ...

Ensuring Consistency of Values Between Child and Parent Components

Is there a way to ensure that the value of submitted in the child component always matches the value of submitted in the parent component? Appreciate any help! @Component({ selector: 'child-cmp', template: ` child:{{submitted}} ...

Having trouble navigating to a child page in Angular 4

When I try to follow the Angular routing & navigation example, I encounter an issue where my page displays as "file not found" when I route. Even when I navigate to the profile page at profile.component.html, I can see my columns, but nothing appears from ...

I am struggling to delete real-time records in Angular using Firestore

I am facing an issue with my Angular code. I want to be able to delete a record and have it reflect in real-time. When I create a product, it works fine, but deleting the product doesn't work unless I refresh the browser. I'm not sure where the p ...

Design an interactive listbox with both HTML and Angular that allows for multiple selections

I am trying to implement a multi select listbox with keyboard navigation capability. Currently, this is the HTML layout I have: <div> <div *ngFor="let tag of tags; let index=index" [class.selectedRow]="rowIsSelected(tag.id) ...

What is the most effective method to retrieve the current browser URL in Angular 2 with TypeScript?

Is there a way for me to retrieve the current URL from the browser within my Angular 2 application? Usually in JavaScript, we would use the window object for this task. Can anyone guide me on how to achieve this in Angular 2 using TypeScript? Appreciate a ...

Ngrx optimized reducer with ahead-of-time compilation

I've been attempting to implement this reducer from the ReduxJs website using NgRx and Angular Cli: function createFilteredReducer(reducerFunction, reducerPredicate) { return (state, action) => { const isInitializationCall = state === ...

Is searching for duplicate entries in an array using a specific key?

Below is an array structure: [ { "Date": "2020-07", "data": [ { "id": "35ebd073-600c-4be4-a750-41c4be5ed24a", "Date": "2020-07-03T00:00:00.000Z", ...

Is there a way to make sure that ngbpopovers stay open even when hovering over the popover content?

I have implemented a ngbpopover to display user information on an element. Currently, the popover is triggered on both hover and click events, but I would like it to remain open when hovered over, instead of closing as soon as the mouse moves away. How c ...

TypeScript: "Implementing" methods. The organized approach

Currently, I am developing a middleware class for Express. Before delving into the details of the class, it's important to note that I will be injecting the middleware later by creating an instance of my "Authenticator" class and then using its method ...

Implement ExpressTS on vercel platform

I have recently developed an Express TypeScript project on GitHub and now I am attempting to deploy it to Vercel. The folder structure of the project is as follows, with 'dist' containing app.js and 'src' containing app.ts. dist dto mi ...

What is the best way to include documentation for custom components using jsDoc?

Within my Vuejs inline template components, we typically register the component in a javascript file and define its template in html. An example of such a component is shown below: Vue.component('compare-benefits', { data() { // By return ...

Learn how to generate specific error messages based on the field that caused the failure of the @Column({ unique: true }) Decorator. Error code 23505

Hey there! I'm currently facing an issue while trying to handle Sign Up exceptions in my code. I want to inform the user if their username OR email is already in use. Although using the decorator @Column({ unique: true}) allows me to catch error 23505 ...

Tips for rendering nested objects and arrays within Angular 2

I am receiving JSON data from an API on the back-end and I want to display it using ngFor. However, when I tried to do so, I encountered an error message stating: "Cannot find a differ supporting object '[object Object]'" in the console. To addr ...