I've created an enum
to organize my new component styles, I need to write multiple ng class expressions or dynamically pass directly to the element call. How can I directly call on element?
button-types.ts
export enum ButtonTypes {
Primary = 'button-primary',
Secondary = 'button-secondary',
Terciary = 'button-terciary',
IconButton = 'button-icon',
}
bo-button.component.html
<button [ngClass]="type">
<i [ngClass]="icon"></i>
{{ label }}
</button>
bo-button.componrny
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ButtonTypes } from './shared/button-types';
@Component({
selector: 'lib-bo-button',
templateUrl: './bo-button.component.html',
styleUrls: ['./bo-button.component.scss']
})
export class ButtonComponent implements OnInit {
@Input() public type: ButtonTypes;
@Input() public icon: string;
@Input() public label: string;
@Input() public arrow: string;
constructor() {
}
ngOnInit() {
}
}
If you assign the ButtonTypes
enum definition to a property of the parent component, you can use that property in the template for data binding with literal enum values. Data binding with properties having enum values also works, like the myButtonType
example below.
import { ButtonTypes } from './button-types.enum';
...
export class AppComponent {
ButtonTypes = ButtonTypes; // <-- Allows to use enum literals in template
myButtonType = ButtonTypes.Secondary; // <-- Specific enum value for binding
}
<lib-bo-button [type]="ButtonTypes.Terciary" label="My terciary button"></lib-bo-button>
<lib-bo-button [type]="myButtonType" label="My button"></lib-bo-button>
The appropriate class style will be applied, assuming that it is defined for each ButtonTypes
value:
button.button-primary {
background-color: dodgerblue;
}
button.button-secondary {
background-color: green;
}
button.button-terciary {
background-color: fuchsia;
}
button.button-icon {
background-color: red;
}
See this stackblitz for a demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With