Does Angular have a declarative way to handle transitions of HTML attributes as it does with CSS atrributes?

24 Views Asked by At

When using Angular animations module is there a way to pass HTML attributes (such as open, inert, etc.) together with the CSS attributes?

I wonder if there's something similar to the style method below, which would take a reference to an html element to set its attributes.

@Component({
  selector: 'app-mycomponent',
  standalone: true,
  templateUrl: './mycomponent.component.html',
  styleUrl: './mycomponent.component.css',
  animations: [
    trigger('onOff', [
      state('on', style({ color: red })),
      state('off', style({ color: black })),
      transition('on <=> off', [animate('400ms 0s ease-out')])
    ])
  ]
})

If that just doesn't exist, can I declare Angular animations inside the class definition so that HTML elements can become available through the @ViewChild decorator (even if I'm not sure how I would stick that inside the trigger's state declarations...)

In general, is there a way in the angular framework to handle HTML attribute transitions in the same declarative way you can do with CSS attributes?

1

There are 1 best solutions below

2
ADITYA On BEST ANSWER

You can't directly manipulate HTML attributes in the same way you manipulate CSS properties using the style() method.

import { Component, ViewChild, ElementRef } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'app-mycomponent',
  templateUrl: './mycomponent.component.html',
  styleUrls: ['./mycomponent.component.css'],
  animations: [
    trigger('onOff', [
      state('on', style({ color: 'red', opacity: 1 })),
      state('off', style({ color: 'black', opacity: 0.5 })),
      transition('on <=> off', [animate('400ms 0s ease-out')])
    ])
  ]
})
export class MyComponent {
  @ViewChild('myElement') myElement: ElementRef;

  currentState = 'on';

  toggleState() {
    this.currentState = this.currentState === 'on' ? 'off' : 'on';
    // Dynamically manipulate HTML attributes
    if (this.currentState === 'on') {
      this.myElement.nativeElement.setAttribute('open', '');
    } else {
      this.myElement.nativeElement.removeAttribute('open');
    }
  }
}