Is there a way to trigger an image flash by hovering over a button using the mouseover feature in AngularJS2?

When I hover over the 'click me' button, I want an image to appear on the webpage. When I stop hovering, the image should disappear using the mouseover option.

This is what I attempted in my app.component.ts and my.component.ts files:

Here is the code for app.component.ts:

import { Component } from '@angular/core';
import { MyComponent } from './my.component';

@Component({
selector: 'my-app',
template: '<h1> Hi Buddy!! </h1>
<mytag></mytag>',
directives: [MyComponent]
})
export class AppComponent { }

And here is the code for my.component.ts:

import { Component } from "@angular/core";

@Component({
selector:'mytag',
template: `<button (mouseover)="<img [src]="image">"  >click me</button>`   // I tried to display image by hovering
})
export class MyComponent{
public image="http://lorempixel.com/400/200";
myclick(klm){
console.log(klm);
}
}

What changes should I make in the class or metadata of my.component.ts to achieve this?

Answer №1

If you want to add animations to your Angular project, the Angular Animations module is the way to go.

Here are the necessary changes for your MyComponent:

import { Component } from '@angular/core'
import { trigger, state, style, transition, animate, keyframes, group } from '@angular/animations';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@Component({
      selector:'mytag',
      template: `<button (mouseover)="toggleOnOff()">click me</button>
                  <img [src]="image" [@switchImageDisplay]="showImage"/>
                  `
      ,
      animations: [
        trigger("switchImageDisplay",[
          state("show", style({
            display : 'block'
          })),
          state("hide", style({
            display : 'none'
          })),
          transition('show <-> hide',[animate('0s')]),
        ])

      ]
    })
export class SwitchDisplayComponent {
      public image="http://lorempixel.com/400/200";
      public showImage : string;
          toggleOnOff(){
            console.log("Previous display value is",this.showImage);
               this.showImage = (this.showImage === "show") ? "hide" : "show";
              console.log("Current display value is",this.showImage);
         }

}

To explain: The toggleOnOff() function switches the variable showImage between show and hide states. The animation trigger named "switchImageDisplay" has two declared states - show and hide, each with their respective CSS properties. A transition is defined with a duration of 0 seconds for switching between these states. Increase the time if you prefer a gradual effect for hiding the image.

In the template code, the img tag is bound to the animation through [@switchImageDisplay]="showImage". Depending on the value of showImage, the state of the animation "switchImageDisplay" is determined.

Don't forget to import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; in your app.module.ts and include it in the imports array.

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

Unable to see Primereact styles reflected on components

After some investigation, I've pinpointed the issue to be related to preflight from tailwind. Upon reviewing the documentation, I came across this helpful information: CSS Layer It seems that using Tailwind CSS with styled or unstyled modes of PrimeR ...

Shiny Chrome, Flexible Flexbox, and plump div elements

Looking to enhance my understanding of flexbox. Encountering a display issue in Chrome where the right column is too wide and the left column is too skinny, while it displays correctly in Firefox. Any suggestions on how to fix this for Chrome? .child ...

I would like to automatically log out when closing the tab in Mozilla, Internet Explorer 8.0, or Chrome

Hello there, I was wondering if it's feasible to end the session and log out when I close my tab. I'd appreciate it if you could confirm whether this feature has been implemented on your end. Thank you, Manish ...

Exploring the Power of ForkJoin in RXJS with Complex Data Structures

I'm looking for a solution using forkJoin to execute an array of objects containing key-value pairs where the value is an observable. The goal is to have each object in the array result in the same key with the corresponding value being the outcome of ...

Extracting the value of an HTML element from a string variable in AngularJS

I am facing an issue with my application where the content of an HTML element is received as a template from the server. I am attempting to assign this template, which is essentially a string, and have the variables within the template linked to the contro ...

Challenges encountered when assigning values in a form with Material UI, Formik, and Typescript

When attempting to set the 'role' and 'active' values on a form, I encountered a couple of issues. The first problem arises from the fact that the selectors' original values are not being properly set. These values are fetched in ...

Attempting to enlarge logo or image when cursor hovers over it

Seeking to enhance logo/image size when cursor hovers over it, but facing an issue where it enlarges even on areas outside of the image itself - View Example. I followed a tutorial to achieve this effect, and specified the width as 1024x1024 for the logo/i ...

Error in Typescript for the prop types of a stateless React component

When reviewing my project, I came across the following lines of code that are causing a Typescript error: export const MaskedField = asField(({ fieldState, fieldApi, ...props }) => { const {value} = fieldState; const {setValue, set ...

How can pipes be utilized on parameters for translation in Angular?

When faced with the task of displaying multiple texts for translation, each containing different parameters like dates, numbers, and currencies, is there a way to effectively nest angular pipes? While I am aware that I can create a proxy object in the com ...

Maintain the spacing of an element when utilizing *ngFor

Using Angular.js and *ngFor to loop over an array and display the values. The goal is to preserve the spaces of elements in the array: string arr1 = [" Welcome Angular ", "Line1", "Line2", " Done "] The ...

Tips for preserving user input from HTML into a text file and then reloading it back into the HTML document

I have recently created a character sheet for a game using HTML. The HTML file is mainly comprised of various input tags such as <input type="text">, <input type="number">, <input type="checkbox">, <input type="radio">, <select&g ...

Elements with inline-block display not aligning horizontally next to each other

I am puzzled as to why the two sections, section.structure and section.specificity, are not aligning properly. It seems that when I reduce the width, they line up correctly at a certain point which I haven't identified yet. My goal is to have the wid ...

What is the reason that the 'mouseenter' event only applies to the initial element in each round of iteration within a spacebar loop?

My goal is to create an off-canvas menu within a template component. I found inspiration from this helpful article. The setup I have is quite common: A container tab where I loop through an items collection An item component that contains the off-canvas ...

Creating three-dimensional text in Three.js

My script is based on this documentation and this resource. Here is an excerpt of my code: <script src="https://raw.github.com/mrdoob/three.js/master/build/three.js"></script> <script> var text = "my text", height = 20 ...

Tips on connecting a font directory from FontAwesome

I am currently attempting to incorporate the fonts provided by FontAwesome for their icons, and they specify that a root folder named Fonts is needed. My attempt to link it was using: <link type="text/css" href="/myPath/font" /> ...

What is the most efficient method for integrating PHP script into HTML code?

When it comes to inserting the full path to every image/css file on my website due to url rewriting, I am searching for the most efficient method. I could simply use: <img src='<?php echo $full_path; ?>/images/theImg.jpg' alt='alt ...

Polling database from various browser tabs

Working on a .NET/angular application that regularly checks the SQL Server database for updates, with the user able to customize the polling interval starting from 10 seconds (as per business requirements). The issue arises when each new tab opened by a ...

"Positioned at the top of the page is the alert box, with the

I'm looking to add an alert at the top of my webpage containing a form for visitors to enter their phone number. Currently, I have a "alert alert-info" div with the form inside it placed at the top of my body tag, which works perfectly. However, when ...

Issues arising from the event target

What is the reason behind this code functioning successfully only when the alert function is called? The color changes after closing the alert box, but if the line with the alert command is commented out, nothing happens. function setLinkColor(el) ...

Hide CSS3 webkit-scrollbar automatically when it's not in use

I need help with customizing scrollbars. How can I hide the scrollbar when it is not needed due to short content? Below is the code snippet I have been working on: .myscroll::-webkit-scrollbar { width: 15px; } .myscroll::-webkit-scrollbar-track ...