Utilizing class variables for animations in Angular 7 component

Currently, I am facing an issue with an animation that is supposed to expand the height on hover. The problem arises because the height of the label is auto-generated and does not animate properly with just the :hover selector. Below is a snippet from my TypeScript @Component file where I have defined the animation:

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css'],
  animations: [
    trigger('buttonState', [
      state('inactive', style({
        height: '100%'
       })),
      state('active', style({
        height: this.buttonHeight
       })),
      transition('inactive => active', animate('1.5s ease-in')),
      transition('active => inactive', animate('1.5s ease-out'))
    ])
  ]
})

The current issue I am encountering is that when trying to access this.buttonHeight, I receive an error stating "Cannot read property 'buttonHeight' of undefined". This leads me to believe that 'this' refers to something other than the class in the @Component or it may not be defined yet. How can I resolve this?

This is how I am calculating the height:

  @ViewChild('button') button : ElementRef;
  buttonHeight : number;

  ngOnInit() {
    this.buttonHeight = this.button.nativeElement.offsetHeight
  }

In the HTML template:

<label [@buttonState]="state" (mouseover)="toggleState()" (mouseout)="toggleState()">

Answer №1

Struggled to get the animation functioning properly, as using this.buttonHeight in the animation did not work. It is necessary to include a parameter:

HTML

<label [@buttonState]="{value: state, params: {buttonHeight: buttonHeight}}" (mouseover)="toggleState()"
    (mouseout)="toggleState()">LABEL</label>

TS

animations: [
    trigger('buttonState', [
      state('inactive', style({
        height: '100%'
      })),
      state('active', style({
        height: "{{buttonHeight}}px"
      }), { params: { buttonHeight: "4" } }),
      transition('inactive => active', animate('1.5s ease-in')),
      transition('active => inactive', animate('1.5s ease-out'))
    ])
  ]

Make sure to assign a default value for each parameter you define to prevent any errors.

I hope this guidance points you in the right direction! (:

Answer №2

There seems to be a challenge in binding this to the component instance because it is being used within an array instead of a function for potential binding. The documentation also does not provide information on this possibility. It might be possible to achieve your goal using CSS.

@Component({
  selector: 'app-create',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css']
})
export class Create implements OnInit {
  @ViewChild('button') button : ElementRef;
  buttonHeight : number;
  isActive = false;

  animate() {
   isActive = !isActive;
   if (isActive) {
     this.buttonState.nativeElment.height = `${this.buttonHeight}px`;
   } else {
     this.buttonState.nativeElment.height = '100%';
   }
  }
  ngOnInit() {
    this.buttonHeight = this.button.nativeElement.offsetHeight
  }

.active {
  transition: all 1.5s ease-out;
}

.inactive {
  transition: all 1.5s ease-in;
}
<label [ngClass]="{active: isActive, inactive: !isActive}" (mouseover)="animate()" (mouseout)="animate()">

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

Combining Two Models in Sails.js

I'm facing an issue with linking two models in sails. I have two models: 'Singer' and 'Country'. In the 'Singer' model, I have an attribute 'singer_country' which represents the id of the 'Country' mod ...

Is it possible to retrieve all data stored in AsyncStorage using React Native, while excluding the

In my current implementation, I am utilizing AsyncStorage.setItem() to store a string key and JSON object in AsyncStorage. For example: https://i.sstatic.net/qjiCD.png However, upon retrieving data from AsyncStorage using getAllKeys() and multiGet(), it h ...

How can I tailor the child count in ag grid to fit my needs?

Currently, I am using ag grid with React and have successfully implemented row grouping. However, the parent rows are displaying child row counts in numeric values. Is there a way to customize the style of the row count? Additionally, I am interested in ca ...

Ways to access the variables of an object that initiated a function, leading to another function being called

I am facing an issue with accessing the variable b from inside the callback of setTimeout. I understand that the callback function of setTimeout only has access to the variables within its surrounding function. How can I access the this.b? Thank you! fu ...

How can I optimize my Javascript applications for better search engine rankings?

Recently, I've been exploring the idea of implementing a fresh workflow process for web development. Yemoan, Grunt, and Bower in conjunction with AngularJS look promising as a solution for front-end development. However, one major drawback is their po ...

Verifying the numerical value of a decimal place

How can I determine if the 4th decimal place in a number is zero or not? I want to throw an error message if it is not zero. For instance, in the number 2.3189, the value of the 4th decimal place is 9. My current code works for most cases, but for exampl ...

Is it possible to implement the bootstrap grid system within my Angular components using grid classes?

Looking for something along the lines of <my-row> <my-col>Content</my-col> <my-col>Content</my-col> </my-row> Having the bootstrap classes within my components. This method was effective with Bootstrap 3, however th ...

Slider Image Fails to Align Properly

I am struggling to align my image slider in the center of my page. It seems like a simple problem to fix, but I can't seem to get it perfectly centered both horizontally and vertically. Any tips on how to achieve this? The CSS code for the image slide ...

Manipulating attributes in a three.js vertex shader and storing values for future processing cycles

Exploring a simple setup concept: https://gist.github.com/ichbinadrian/4758155 The idea is to color fragments based on their distance from the lowest or highest vertex, like a mountain range. How can I store a value in the shader for future processing, co ...

Redux does not cause the components to re-render

One of my components is designed to extract data from the mapStateToProps() method. Here is the code for this component: handleClick = () => { if (this.props.data.status) { this.props.changeIpStatus(index, !this.props.data.statu ...

While conducting tests on a Vue single file component, Jest came across an unforeseen token

I need help with setting up unit tests for my Vue application that uses single file components. I've been trying to use Jest as mentioned in this guide, but encountered an error "Jest encountered an unexpected token" along with the details below: /so ...

Issue with Discord.js (14.1) - Message Handling Unresponsive

After developing a sizable Discord Bot in Python, I decided to expand my skills and start learning JS. Despite thoroughly studying the documentation and comparing with my original Python Bot regarding intents, I am facing difficulties getting the message ...

The $.get route is failing to execute on the server-side, resulting in no data being retrieved. The server is not logging any information about this

I'm facing an issue where the $.get method is no longer working for me. I have simplified my code as much as possible, but it still doesn't work. Here is the code snippet: $("#test").click(function() { console.log("I'm in the on click e ...

Utilizing Three.js with interactive functionalities and advanced transformation controls

I'm facing an issue with my project where I am using three.interaction to capture click events on certain objects and add transformControls to them. The problem I'm encountering is that the transform controls seem to block the click event on oth ...

Getting the route parameter in Angular 2 is easy with the stable router

Currently working with the latest stable Angular 2 RC version. Unfortunately, the documentation for the new router component has yet to be completed. Struggling to retrieve a parameter from a navigated page. Defined routes: @Routes([ {path: '/resu ...

Fluctuating Values in Array Distribution

I have a set of users and products that I need to distribute, for example: The number of values in the array can vary each time - it could be one value one time and three values another time. It is important that each user receives a unique product with ...

The React material-table only updates and rerenders the table when the data is updated twice

Currently, I am utilizing a tool called material-table (check it out here: https://material-table.com/#/) which has been developed using React. The issue I am facing is that the data passed as a prop to material-table doesn't seem to update correctly ...

What is the method to set up the "materializecss" modal with the "before" (beforeload) feature?

Trying to implement the modal functionality in my project using the materializecss framework but facing some challenges. I have created a popup modal for an image with the code below: HTML: <div class="media-insert"> <a href="#img2" class="moda ...

AngularJS: dependent dropdown menus

Attempting to create a cascade dropdown in Angular, I assumed it would work seamlessly with binding. Here is the code snippet: <select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients track by c.id" req ...

How to deal with jQuery's set val() behavior on SELECT when there is no matching value

Let's say I have a select box like this: <select id="s" name="s"> <option value="0">-</option> <option value="1">A</option> <option value="2" selected>B</option> <option value="3">C</option> </ ...