Using *ngFor to iterate through elements with distinct styles

Is there a way to assign different classes to buttons generated using *ngFor without changing the class for all previously created buttons when toggled? I have 2 search bars adding text to the same array, displayed as buttons. I want to differentiate between data from searchbar1 in blue and searchbar2 in orange, while maintaining the order of selection.

newAction(text){
  this.classvalue = true;
  this.ConvMsgs.push("ChatBot: "+text);
    console.log(text);
  }
newIntent(text){
  this.classvalue =false;
this.ConvMsgs.push("User: "+text);
  console.log(text);
}
.msg_cotainer{
        margin-top: auto;
        margin-bottom: auto;
        margin-left: 10px;
        border-radius: 25px;
        background-color: #39adc7;
        padding: 10px;
    position: relative;
  }
  .msg_cotainer2{
        margin-top: auto;
        margin-bottom: auto;
        margin-left: 10px;
        border-radius: 0px;
        background-color: chocolate;
        padding: 10px;
    position: relative;
  }
<ng-container *ngFor="let button of ConvMsgs">
                  <br />
                  <button [ngClass]="classvalue? 'msg_cotainer':'msg_cotainer2'">{{button}}</button>
                  <br />
                </ng-container>

These functions are triggered when clicking on search bar results.

Answer №1

When attempting to show a message, consider passing the message as an object rather than a string. Utilizing an object with text and class properties allows for customization of the message's appearance through the class property.

Here's an example that you can experiment with on StackBlitz.

app.component.html

<button *ngFor="let message of messages" [ngClass]='message.class'>{{message.text}}</button>

app.component.css

.action {
  background: red;
}
.intent {
  background: green;
}

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  messages = [];

  ngOnInit() {
    this.newAction('Action 1');
    this.newAction('Action 2');
    this.newIntent('Intent 1');
  }

  newAction(text){
    this.messages.push({
      text: `Chatbot ${text}`,
      class: 'action'
    });
  }
  newIntent(text){
    this.messages.push({
      text: `User: ${text}`,
      class: 'intent'
    });
  }
}

Answer №2

It is recommended to utilize a boolean variable within the ConvMsgs object:

newMessage(text){
    this.ConvMsgs.push({
        text: "ChatBot: "+text,
        isChatBot: true
    });
    console.log(text);
}
newUserInput(text){
    this.ConvMsgs.push({
        text: "User: "+text,
        isChatBot: false
    });
    console.log(text);
}
<ng-container *ngFor="let message of ConvMsgs">
    <br />
    <button [ngClass]="message.isChatBot ? 'chatbot_message' : 'user_message'">{{ message.text }}</button>
    <br />
</ng-container>

Answer №3

If you find yourself with a limited number of buttons to display, you can utilize the array index to determine which class to apply. Here's an example:

<ng-container *ngFor="let button of ConvMsgs; let i = index">
    <br />
    <button [ngClass]="'message_container' + i">{{ button.text }}</button>
    <br />
</ng-container>

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

Is it possible to change a Material UI style without resorting to an HOC?

Is there any method to modify the styling of a Material UI component without the need to create an entirely new component using withStyles()? For example, if I am currently displaying the following and simply want to adjust the color of the "Delete" label ...

Having trouble getting my local website to load the CSS stylesheet through Express and Node.js in my browser

https://i.stack.imgur.com/qpsQI.png https://i.stack.imgur.com/l3wAJ.png Here is the app.js screenshot: https://i.stack.imgur.com/l3wAJ.png I have experimented with different combinations of href and express.static(""); addresses. However, I am ...

Customizable dropdown menu design using HTML and CSS

Hello everyone, this is my very first post on Stack Overflow and I'm a bit unsure about the rules regarding posting. Please feel free to point out any mistakes I may have made. I've searched through the forums but haven't found a clear answe ...

"Troubleshooting: Module not found" (Getting started with Jest in a nested project connected to a shared directory)

I've recently taken over a project that contains the following folder structure: node_modules/ server/ ├── node_modules/ ├── src/ │ └── helpers/ │ ├── updateTransactions.ts │ └── updateTransactions.tes ...

Having trouble accessing the 'add' property of Rxjs Subscription

I have been working on optimizing my code and I encountered an issue with unsubscribing from multiple subscriptions in ngOnDestroy. Specifically, when trying to invoke the add() method to include additional child subscriptions, I keep getting an error me ...

Angular 7 - Implementing periodic JSON data retrieval from server and maintaining local storage within Angular application

Seeking guidance on how to handle updating a static json file stored in the assets directory in an Angular 7 project. The goal is to periodically fetch a json from a server, check for updates, and perform post-processing on the data in the static file (ess ...

Angular 10 - Understanding the R3InjectorError in AppModule related to Window constant injection

I'm attempting to access the window object in Angular using a service that can be injected. import { Injectable } from '@angular/core'; function _window(): any { return window; } @Injectable({ providedIn: 'root' }) export cla ...

Uploading Files with Angular 2 using AJAX and Multipart Requests

I am currently working with Angular 2 and Spring MVC. At the moment, I have an Upload component that sends an AJAX request to the Spring backend and receives a response containing parsed data from a .csv file. export class UploadComponent { uploadFile: f ...

Updating a list item in AngularFire2 triggers a change in the overall list

I have successfully implemented an update call to Firebase, but I am experiencing an issue where the list on which I am looping is being refreshed, causing my input field to lose focus. Is there a way for me to trigger the update without refreshing the or ...

Text color wave effect - mimic a block of colors flowing through text

I'm experimenting with creating a unique text effect where, upon hovering over the text, it appears as though a block of color is passing through it. Inspired by the technique showcased in this first example (specifically for the word "Kukuri"), I ut ...

Using data analysis to customize the appearance of boundaries across various map styles - Google Maps Javascript API V3

Utilizing data-driven styling for boundaries in Google Maps Javascript API V3 is a fantastic feature that appears to be compatible with all map types such as terrain, satellite, and hybrid. Nevertheless, I have encountered difficulties in making it visible ...

Tips for resolving the final item issue in Owl Carousel when using right-to-left (RTL)

Encountering a bug with the rtl setting in owl-carousel. When the rtl is applied to the slider and I reach the last item, the entire slider disappears! Here's the code snippet: var viewportWidth = $("body").innerWidth(); if (viewportWidth & ...

Unable to eliminate a persistent purple dashed section within the div

After gaining some knowledge of CSS and flexbox, I decided to create a Landing brochure site. However, I encountered an issue that I couldn't solve on my own during the building process. I'm attempting to eliminate the Purple dashed area by exten ...

Troubleshooting Socket-io Client Problem After Migrating to TypeScript

I am currently in the process of migrating my MERN stack + Socket.io template to Typescript. However, I am encountering some issues specifically when transitioning the client code to Typescript. The Problem: My socket pings from socket.io-client are faili ...

The appearance of a printed webpage does not match what is shown in Google Chrome's Print Preview feature

I have encountered a strange issue that has me stumped. I need the webpage in my current project to be completely printable, but I'm facing difficulties. While the signature field and note field (with the text "erererer") display perfectly in Google C ...

Issues with the rating plugin functionality in Ionic 3

After following the instructions in this tutorial: http://ionicframework.com/docs/native/app-rate/ Even though I implemented the second method, I encountered the following error: Uncaught (in promise): TypeError: Cannot read property 'split' ...

Using the `ngrx` library to perform an entity upsert operation with the

I am facing a certain challenge in my code. I have an action defined as follows: export const updateSuccess = createAction('Success', props<{ someId: string }>()); In the reducer, I have an adapter set up like this: export const adapter: ...

Tips for maintaining the footer at the bottom of the page regardless of the screen size

In my current project, I am dealing with several web pages. For each page, I have arranged three div tags: Header Body (content) Footer The issue arises when it comes to the body div tag, which houses the main content of a page such as forms and descrip ...

The footer element is missing from the body section of the HTML code, causing the box shadow to not encompass the footer as intended

Having a problem in CSS where the footer is not appearing within the body element in the HTML code. The footer is placed between the body tags, but the box shadow defined for the body is not being applied to the footer. The code snippet below shows the CSS ...

Merge two attributes into a single entity using RxJS

Currently, I am working on handling HTTP responses in the Angular framework and I have a requirement to merge two properties using rxjs. Let's consider a sample response from an API where I need to combine the age with birthday. Since the HTTP respon ...