【问题标题】:How to change the color of a button on Bootstrap and Angular如何更改 Bootstrap 和 Angular 上按钮的颜色
【发布时间】:2021-08-01 03:56:06
【问题描述】:

默认情况下,按钮是红色的。例如,当用户输入 2 个数字时,按钮应变为蓝色。如何在 Bootstrap 和 Angular 上创建此开关?

这是在我的模板中:

<div class="col-12 col-md-4 text-center" [ngClass]="{'success': otp?.length == 2 ? true : false}">
  <button class="customButton" (click)="signin()">
      ok
  </button>
</div> 

这是Stackblitz。

【问题讨论】:

  • 请分享其余代码,“用户输入 2 个数字”是什么意思?如果您能创建一个最小的可重现示例,那就太好了
  • 为什么不能根据你提供的条件创建2个按钮并添加ngIf
  • 如果您创建Stackblitz,我们可以更轻松地帮助您解决问题。
  • 您可能希望批准对问题的更改,然后在此处添加 stackblitz 链接。检查对我的答案的评论,了解我为使您的 stackblitz 工作所做的工作。干杯
  • @H3AR7B3A7 :是的...对不起,我批准了您的修改...

标签: angular bootstrap-4


【解决方案1】:

使用[类]

在模板中:

[class.success]="otp?.length === 2"

在样式表中:

.success{
  background-color: blue;
}

使用 [ngClass]

在模板中:

[ngClass]="{ blue: otp?.length === 2 }"
[ngClass]="getClass()"

在component.ts中:

getClass() {
  const isLongEnough = otp?.length === 2
  return { success: isLongEnough }
}

或者:

getClass() {
  if(otp?.length === 2)
    return 'blue'
  return ''
}

或者:

getClass() {
  if(otp?.length === 2)
    return ['blue']
  return []
}

使用[样式]

在模板中:

[style.color]="'blue'"

使用 [ngStyle]

在模板中:

[ngStyle]="{ 'background-color': otp?.length === 2 ? 'blue' : 'red' }"
[ngStyle]="getStyle()"

在component.ts中:

getStyle() : any {
  if(otp?.length === 2)
    return { 'background-color': 'blue' }
  return {}
}

【讨论】:

  • 作为旁注,bootstrap 已经有自己的按钮颜色类。但我想你已经阅读了docs 并想使用自己的配色方案。
  • 非常感谢您的帮助和解释。我的问题是我不明白如何更改引导程序上按钮的颜色?我在这里编辑了我的代码stackblitz.com/edit/angular-ivy-6xfea7?file=src/app/… 当用户输入 2 个数字时,按钮必须改变颜色...
  • 如果你只想让按钮改变颜色,你应该这样写:[ngClass]="{'success': otp?.length === 2 ? true : false}" 在按钮标签上,而不是包装 div。并创建一个 css 类,例如:.success{ background-color: blue; } 只是那些改动,为我修好了。
【解决方案2】:

你试过这样吗?

[ngClass]="{'success': otp?.length == 2}"

【讨论】:

    猜你喜欢
    • 2020-12-28
    • 2018-11-23
    • 1970-01-01
    • 2020-02-01
    • 2013-07-31
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多