[英]Dynamically displaying Bootstrap Classes in ng2
I am trying to display dynamic classes for Bootstrap alerts by using Angular 2.我正在尝试使用 Angular 2 显示 Bootstrap 警报的动态类。
If the MessageType
is 1, I want to display Success message and 2 for Error message.如果
MessageType
为 1,我想显示 Success 消息和 2 为 Error 消息。 Please see the sample below请看下面的示例
<div class="alert alert-success" role="alert">
Your data has been saved successfully.
</div>
<div class="alert alert-danger" role="alert">
Error occurred!!! Try again.
</div>
I tried to do the dynamic class like the following, but it doesn't work at all:我试图做如下动态类,但它根本不起作用:
<div [ngClass]="['alert', 'alert-success': MessageType == 1, 'alert-danger' : MessageType == 2]" *ngIf="Message">
{{Message}}
</div>
add-todo.component.ts添加-todo.component.ts
export class TodoAddComponent {
Message: string;
MessageType: number;
AddItem(): void {
// do some processing
this.Message = "New Item has been added";
this.MessageType = 1;
}
}
How can I display the class 'alert-success' or 'alert-danger' dynamically in the Html?如何在 Html 中动态显示“alert-success”或“alert-danger”类? Should I do it like this according to the result and use it back in html?
我应该根据结果这样做并在html中使用它吗?
alertClass: string;
this.alertClass = 'alert-success'; // if it succeeds
this.alertClass = 'alert-danger'; // if it fails
You could also bind directly to class with the required alert-x class:您还可以使用所需的 alert-x 类直接绑定到类:
<div *ngIf="Message"
class="alert"
[class.alert-success]="MessageType == 1"
[class.alert-danger]="MessageType == 2">
{{Message}}
</div>
Pass an object to [ngClass]
instead of an array, because right now you're trying to pass invalid array-object hybrid.将对象传递给
[ngClass]
而不是数组,因为现在您正在尝试传递无效的数组对象混合。
Use array to just tell which classes you want to use.使用数组只是告诉您要使用哪些类。
Use object to include conditions making specific classes appear/disappear.使用 object 来包含使特定类出现/消失的条件。
<div [ngClass]="{alert: true, 'alert-success': MessageType == 1, 'alert-danger': MessageType == 2 }" *ngIf="Message">
{{Message}}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.