I created a CSS keyframe animation for a form field to expand on focus via scaleX
.
@keyframes formField {
0% {
transform: scaleX(1);
}
50% {
transform: scaleX(1.03);
}
80% {
transform: scaleX(.98);
}
100% {
transform: scaleX(1);
}
}
But the drawback is since form fields are different widths, they expand different amounts. My client would like all the form fields to expand the same amount (e.g. 10 px) regardless of their width. So I can't use scaling by a factor (e.g. scaleX(1.03)
).
So, I don't think I can use CSS transforms for this.
Next, I thought I might create an Angular directive that gets the pixel width of the object it's applied to, increment the width by 10px and return it to the original width, with transitions.
Edit
So I have created this directive:
import { ElementRef, HostListener, Component } from '@angular/core';
import { trigger, state, style, animate, transition } from '@angular/animations';
@Component({
/* tslint:disable-next-line:component-selector */
selector: '[focusField]',
animations: [
trigger('isFocused', [
transition('*<=> *', [
style({ transform: 'scaleX(1)' }),
animate(200, style({ transform: `scaleX(${this.scaleFactor})` }))
])
])
],
template: `
<ng-content></ng-content>
`
})
/* tslint:disable-next-line:component-class-suffix */
export class FocusFieldDirective {
constructor(private _elementRef: ElementRef) {}
fieldWidth: number;
scaleFactor: number;
@HostListener('focus', ['$event'])
onFocusField(event: MouseEvent): void {
this.fieldWidth = this._elementRef.nativeElement.offsetWidth;
this.scaleFactor = this.fieldWidth + 10 / this.fieldWidth;
}
}
On focus on the input field with the directive applied, I correctly get the element's width and the scale factor. However, I'm getting an error trying to use the scaleFactor in the animation, with this line:
animate(200, style({ transform: `scaleX(${this.scaleFactor})` }))
The error thrown: TypeError: undefined is not an object (evaluating 'this.scaleFactor')