Utilizing ng-class to apply separate conditions to an array of buttons in Angular

I am facing a straightforward issue. I need to create an array of 3 buttons, and upon clicking each button, the background color of the page should change. The catch is that I have to achieve this using pure Angular-TypeScript without the use of JavaScript functions. I believe I need to utilize ng-class to set conditions for the buttons, but I'm unsure how to proceed. I've managed to create the array of three buttons successfully, but I seem to be stuck at this point. I would greatly appreciate it if you could provide a solution. Below is the snippet from my component.ts file

buttons = [
{
  name: 'Red',
  id: 'btn1'
},
{
  name: 'Green',
  id: 'btn2'
},
{
  name: 'Blue',
  id: 'btn3'
}
];

getColor(id) {
switch (id) {
  case 'btn1':
    return 'red';
  case 'btn2':
    return 'green';
  case 'btn3':
    return 'blue';
}
}

Here is the attempted html code.

<div *ngFor="let button of buttons">
  <button [ngStyle]="{'background-color':getColor(button.id)}">
  {{ button.name }}</button>
</div>

I tried using ng-style, which did not yield expected results. Kindly advise on how I can implement a solution using ng-class instead.

Answer №1

If you want to customize the background color of buttons using inline CSS, you can simply use button.name in your styling.

<div *ngFor="let button of buttons">
  <button [ngStyle]="{'background-color': button.name}">
  {{ button.name }}</button>
</div>

You can also refer to this link for more information:

https://stackblitz.com/edit/angular-ufnq8p?file=src%2Fapp%2Fapp.component.html

Answer №3

Revamp your HTML page with the following changes

<div [ngStyle]="{'background-color': color}">
    <hello name="{{ name }}"></hello>
     <p>Begin customizing to witness some magic happen :)
     </p>
    <div *ngFor="let button of buttons">
     <button (click)="color=button.name" >
    {{ button.name }}</button>
  </div>
</div>

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

Having trouble getting a local npm installation to work from a specific file path?

After following the instructions from this helpful link to install an npm package through a file path, I encountered an error when attempting to use it: Cannot find module '<module_name>' or its corresponding type declaration Are there an ...

I am facing difficulty transitioning from iframe to the Angular App

I have attempted various solutions from stack overflow to switch to an iframe using ProtractorJS, but none of them have successfully worked for me. I am seeking help from someone who has faced a similar issue and could provide some guidance. The Issue: Wh ...

Ensuring the image is properly sized to fit the screen and enabling the default zoom functionality

I am looking to achieve a specific behavior with an image, where it fits the viewport while maintaining its aspect ratio and allowing for zooming similar to how Chrome or Firefox handle local images. Here are the details of my project: The image I have is ...

Develop a wrapper for a function with multiple variations in TypeScript

Encountering an issue with the code below while attempting to create a proxy for a function with multiple overloads: // The target function function original (a: number): boolean; function original (a: string): boolean; function original (a: boolean): bool ...

Determining the total number of items in an array in Angular efficiently without causing any lag

Currently, I am using the function checkDevice(obj) to validate if a value is present or not. In addition to this functionality, I also require a separate method to determine the number of occurrences of Device in the Array. component.ts public checkDevi ...

Issue: [HPM] Context not recognized. Please specify a valid context such as: "/api" or ["/api", "/ajax"]

Suddenly, I am encountering the following error in my Angular 7 project without making any changes. Strangely, it was working fine until yesterday. Error: [HPM] Invalid context. Expecting something like: "/api" or ["/api", "/ajax"] at Object.matchContext ...

What strategies can I employ to prevent redundancy when all my .vue files are identical?

Although I am new to Vue, there are many aspects that I find appealing. However, one thing I dislike is combining templates, scripts, and styles in the same file. Instead, I prefer separating these concerns by using: <template src="./template.html"> ...

When processing JSON data, Typescript is unable to interpret a map<string,string> structure

I am currently working with Angular5 within a spring boot application and I am attempting to retrieve a Map object in JSON format. Spring : //sample method return ResponseEntity.ok((new Gson()).toJson(/*My map object*/)); Angular5 : sql_list = new Map& ...

Tips on filtering an array in a JSON response based on certain conditions in Angular 7

Looking to extract a specific array from a JSON response based on mismatched dataIDs and parentDataIDs using TypeScript in Angular 7. { "data":[ { "dataId":"Atlanta", "parentDataId":"America" }, { "dataId":"Newyork", ...

Oops! Looks like there was an issue with assigning to a reference or variable: Error: Uncaught (in promise)

I seem to be struggling with an issue that I believe may have been addressed before, but after reviewing other solutions, I am unable to pinpoint the error in my code. Any assistance in identifying my mistake would be greatly appreciated. <div class="j ...

Should I link my Angular Material 2 data table to AngularFire2 or Firebase service?

Trying to make this work has been quite the struggle. I've spent hours experimenting, but nothing seems to be working as expected. The md data table is relatively new, so there isn't much information available online yet. Connecting Firebase to t ...

Derivation of the general function parameter

To provide a solution to this problem, let's consider the example below where a function is used. The function returns the same type that it accepts as the first argument: function sample<U>(argument: (details: U) => U) { return null; } ...

Show the current time using Moment.js

I am currently working on developing a clock component that displays the current time in real-time. Issue: The initial time is correctly displayed when the page loads (HH:mm A), but the clock does not update dynamically. clock.component.ts : import { ...

How to detach functions in JavaScript while preserving their context?

Can functions in JavaScript be detached while still retaining access to their context? For instance, let's say we have an instance of ViewportScroller called vc. We can retrieve the current scroll position with the following method: vc.getScrollPosi ...

Exploring Typescript: A guide to iterating through a Nodelist of HTML elements and retrieving their values

I'm struggling to retrieve values from a Nodelist of input elements. Can anyone help me out? let subtitleElements = document.querySelectorAll( '.add-article__form-subtitle' ); ...

What method can be used to start an Angular app without the need for recompilation?

When I first created my Angular app, I used the command ng serve to build and run it. This command produced the following output: 10% building 3/3 modules 0 activei 「wds」: Project is running at http://localhost:4200/webpack-dev-server/ i 「wds」: we ...

Filter that caters to specific number of properties of X

Looking to create a versatile filter function that can handle multiple criteria? Here's a snippet of the current filtering function: const filterRows = () => { items.filter((item) => { if(selectedDrinks.length > 0 && select ...

Show all the input validation errors in Angular 4

I'm currently in the process of developing my first Angular 4 application. I am working on testing form validation using a template-driven approach and have added some validators to my form. Now, I am looking for a way to display validation errors fo ...

Achieving CommonJS imports compilation with Typescript

In my TS file, I've included a 3rd party package using import XXX { YYY, ABC, 123 } from 'XXX'; While it compiles to CommonJS without any issues, I'd prefer to have it compiled to an ESModule instead. I tried changing the target and mo ...

What is the best way to hide the MatSlidePanel?

There is a side panel in my application that I need to close upon user action. I am facing an issue with the following error message: Property 'close' does not exist on type 'MatSlidePanel'.ts(2339) Below is the code snippet I attempte ...