"Utilize ngclass to set CSS classes based on enum string values

Is there a way to directly call an element in Angular when using an enum to organize component styles? Instead of writing multiple ng class expressions or dynamically passing them to the element call.

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() {
  }    
}

Answer №1

When you link the ButtonTypes enum definition to a property of the parent component, you gain the ability to utilize that property in the template for data binding with literal enum values. Data binding with properties that contain enum values is also possible, as demonstrated in 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 tertiary button"></lib-bo-button>
<lib-bo-button [type]="myButtonType" label="My button"></lib-bo-button>

The corresponding class style will be applied, provided it is defined for each ButtonTypes value:

button.button-primary {
  background-color: dodgerblue;
}

button.button-secondary {
  background-color: green;
}

button.button-tertiary {
  background-color: fuchsia;
}

button.button-icon {
  background-color: red;
}

For a demonstration, check out this stackblitz.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message in Typescript with React: "The type 'ComponentClass<StyledComponentProps<{}>>' cannot be assigned to type 'typeof MyComponent'"

Currently experimenting with integrating the Material UI 1.0 (beta) @withStyles annotation into a React component. The documentation provides a JavaScript example (), however, it results in a compilation error when using Typescript. Despite the error, the ...

What is the best way to bring two useStyles files into a single TypeScript file?

I am having an issue with finding a declaration file for the module 'react-combine-styles' even after I installed it using npm install @types/react-combine-styles. import React, { useState } from "react"; import useStyles from "./u ...

Angular 5 facing issue with loading external scripts dynamically

I have configured the external scripts in the .angular-cli.json file under the scripts property: ` "scripts": [ "../src/assets/plugins/jquery/jquery.min.js", "../src/assets/plugins/popper/popper.min.js", "../src/assets/plugins/jquer ...

The server's response is unpredictable, causing Json.Parse to fail intermittently

I have encountered a strange issue that is really frustrating. It all started when I noticed that my Json.Parse function failed intermittently. Here is the code snippet in question: const Info = JSON.parse(response); this.onInfoUpdate(Info.InfoConfig[0]); ...

The iframe is not large enough to contain all the HTML content

I'm encountering a problem with a website I'm currently developing - specifically, I am struggling to embed an HTML document into an iframe in a manner that fills the entire page. Additionally, I am utilizing Angular to retrieve the HTML document ...

Utilizing Mongoose Typescript 2 Schema with fields referencing one another in different schemas

I'm currently facing an issue as I attempt to define 2 schemas in mongoose and typescript, where each schema has a field that references the other schema. Here's an example: const Schema1: Schema = new Schema({ fieldA: Number, fieldB: Sch ...

Creating a unique directive to customize the height

I'm currently working on a directive called appHeaderResize, which is designed to calculate the height of both the <app-online-header> component and the <app-navigation> component. Below is the code snippet: <div class="sticky" appHe ...

Utilizing the 'as' prop for polymorphism in styled-components with TypeScript

Attempting to create a Typography react component. Using the variant input prop as an index in the VariantsMap object to retrieve the corresponding HTML tag name. Utilizing the styled-components 'as' polymorphic prop to display it as the select ...

Ways to eliminate the dynamically included angular files from the .net core web api project

Embarking on a new project, I aim to utilize asp.net core web.api and angular 9. My initial goal is to establish a .net core web api project without MVC or scaffolded angular project. What I desire is to have the spa launch along with the web.api, mirrorin ...

Having trouble getting the styles property to work in the component metadata in Angular 2?

Exploring Angular 2 and working on a demo app where I'm trying to apply the styles property within the component metadata to customize all labels in contact.component.html. I attempted to implement styles: ['label { font-weight: bold;color:red } ...

I encountered difficulty in testing the Angular Material Select Component due to complications with the CDK Test Harness

While working on testing a component that utilizes Angular Material Components, I came across the CDK Test Harness and decided to use it to retrieve the count of options in the Mat Select component. You can find more information about the CDK Test Harness ...

I'm facing an issue where the ion-select component is not displaying the selected value when

Whenever I apply formcontrolname to an ion-select element, the initially selected value does not appear. It only becomes visible when I interact with the select element or use setTimeout(): html: <form [formGroup]="formGroup"> ...

Can you explain the meaning of <T = MyType>?

While exploring a TypeScript file, I stumbled upon this interface declaration: interface SelectProps<T = SelectValue> extends AbstractSelectProps { /* ... */ } I've searched through the TypeScript handbook for <T = but couldn't find an ...

Is there a simple method I can use to transition my current react.js project to typescript?

I am currently working on a project using react.js and am considering converting it to typescript. I attempted following an article on how to make this conversion but have run into numerous bugs and issues. Is there a simpler method for doing this conver ...

Is Axios the sole option for API calls when utilizing Next.js with SSG and SSR?

Can someone clarify the best practice for data fetching in Next.js? Should we avoid using axios or other methods in our functional components, and instead rely on SSG/SSR functions? I'm new to Next.js and seeking guidance. ...

Tips for exporting/importing only a type definition in TypeScript:

Is it possible to export and import a type definition separately from the module in question? In Flowtype, achieving this can be done by having the file sub.js export the type myType with export type myType = {id: number};, and then in the file main.js, i ...

Setting up webpack to compile just the necessary assets for running an Angular 5 application

I am currently using Angular 5 and I encountered a situation when running the following command: ng build --prod --named-chunks --aot This command generated numerous files and folders in the 'dist' directory: [development a85a7dc] Initial dist ...

Issues resolving the signature of a parameter in a Typescript decorator within vscode

I encountered an error while attempting to decorate a class in my NestJS service. The Typescript code compiles without any issues, but I am facing this problem only in VSCode. Unable to resolve signature of parameter decorator when called as an expression ...

Could Typescript decorators be used as mixins?

In the process of developing a complex Angular2 application, I have created a base class that serves as the foundation for my components: export abstract class ReactiveComponent implements OnInit, OnDestroy, AfterViewInit { abstract ngOnInit(): void; ...

Is there a way to programmatically add a timestamp to a form in Angular6?

Is there a way to automatically populate new forms with the current datetime value? this.editForm.patchValue({ id: chatRoom.id, creationDate: chatRoom.creationDate != null ? chatRoom.creationDate.format(DATE_TIME_FORMAT) : null, roo ...