Skip to content

Instantly share code, notes, and snippets.

@pjlamb12
Created February 2, 2021 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjlamb12/4cab4f7181aafccb8c9105a64af233fa to your computer and use it in GitHub Desktop.
Save pjlamb12/4cab4f7181aafccb8c9105a64af233fa to your computer and use it in GitHub Desktop.
Custom Tailwind Button Directive
export const DEFAULT_BUTTON_STYLES =
'px-5 py-3 text-white text-sm text-center uppercase font-semibold tracking-wide rounded-lg hover:shadow-md focus:outline-none focus:shadow-outline transition duration-300';
export const BUTTON_COLOR_STYLES = {
orange: 'bg-orange-500 hover:bg-orange-600 active:bg-orange-600',
green: 'bg-green-500 hover:bg-green-600 active:bg-green-600',
red: 'bg-red-500 hover:bg-red-600 active:bg-red-600',
blue: 'bg-blue-500 hover:bg-blue-600 active:bg-blue-600',
};
import { Directive, HostBinding, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { BUTTON_COLOR_STYLES, DEFAULT_BUTTON_STYLES } from './button-styles.util';
@Directive({
selector: '[twButton]',
})
export class ButtonDirective implements OnInit, OnChanges {
private defaultClasses: string = DEFAULT_BUTTON_STYLES;
@Input('twButton') buttonColor: string;
@HostBinding('class')
elementClass: string = `${this.defaultClasses}`;
ngOnInit() {
this.setColor();
}
ngOnChanges(change: SimpleChanges) {
if (change?.mmButton?.currentValue !== change?.mmButton?.previousValue) {
this.setColor();
}
}
setColor() {
if (this.buttonColor) {
this.elementClass = `${this.defaultClasses} ${BUTTON_COLOR_STYLES[this.buttonColor] || ''}`;
} else {
this.elementClass = `${this.defaultClasses}`;
}
}
}
<button twButton="blue">My Blue Button</button>
<a twButton="orange" href="#">My Orange Link Button</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment