Css *用于不同类别的元素

Css *用于不同类别的元素,css,angular,typescript,Css,Angular,Typescript,我正在尝试为使用*ngFor生成的按钮创建不同的类。但是一旦我切换了这个类,它就会改变以前创建的所有按钮的类,我知道这是合乎逻辑的,但我希望有一种方法 *更多上下文:我有两个搜索栏,都将它们的文本添加到同一个数组中。数组的内容以按钮显示。我想区分输入的数据,所以来自蓝色搜索栏1和橙色搜索栏2的文本,同时保持选择顺序,这就是为什么我没有将它们分成两个按钮的原因 newAction(文本){ this.classvalue=true; this.ConvMsgs.push(“聊天机器人:+text

我正在尝试为使用*ngFor生成的按钮创建不同的类。但是一旦我切换了这个类,它就会改变以前创建的所有按钮的类,我知道这是合乎逻辑的,但我希望有一种方法

*更多上下文:我有两个搜索栏,都将它们的文本添加到同一个数组中。数组的内容以按钮显示。我想区分输入的数据,所以来自蓝色搜索栏1和橙色搜索栏2的文本,同时保持选择顺序,这就是为什么我没有将它们分成两个按钮的原因

newAction(文本){
this.classvalue=true;
this.ConvMsgs.push(“聊天机器人:+text”);
console.log(文本);
}
新意图(文本){
this.classvalue=false;
this.ConvMsgs.push(“用户:+text”);
console.log(文本);
}
.msg\u cotainer{
页边顶部:自动;
页边距底部:自动;
左边距:10px;
边界半径:25px;
背景色:#39adc7;
填充:10px;
位置:相对位置;
}
.msg_cotainer2{
页边顶部:自动;
页边距底部:自动;
左边距:10px;
边界半径:0px;
背景颜色:巧克力色;
填充:10px;
位置:相对位置;
}


{{按钮}

您应该在ConvMsgs中使用布尔值:

newAction(text){
    this.ConvMsgs.push({
        text: "ChatBot: "+text,
        classvalue: true
    });
    console.log(text);
}
newIntent(text){
    this.ConvMsgs.push({
        text: "User: "+text,
        classvalue: false
    });
    console.log(text);
}


{{button.text}

如果只有已知数量的按钮要渲染,可以尝试使用数组的索引来确定应用了哪个类,如下所示:



{{button.text}

当您试图通过以字符串形式传递消息来显示消息时。如果要传递具有文本和类属性的对象,则可以使用该类属性设置自定义类

下面是一个例子,你也可以在这里尝试

app.component.html

<button *ngFor="let message of messages" [ngClass]='message.class'>{{message.text}}</button>
应用程序组件.ts

.action {
  background: red;
}
.intent {
  background: green;
}
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'
  });
}
}

谢谢你的建议,结果很好。
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'
  });
}
}