Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass to ngclass enum string value

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() {
  }    
}
like image 800
Vitor Piovezam Avatar asked Sep 18 '25 01:09

Vitor Piovezam


1 Answers

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.

like image 199
ConnorsFan Avatar answered Sep 20 '25 15:09

ConnorsFan