【问题标题】:how to dynamically change background color of a button in angular material without the need to click on it如何动态更改角度材料中按钮的背景颜色而无需单击它
【发布时间】:2021-10-30 10:17:06
【问题描述】:

我正在尝试使用 Angular 材质构建网页 我有一个下拉选择元素和一堆 FAB 按钮来显示状态。 我想做的是,如果单击下拉列表并选择一个项目。 按钮的背景颜色会根据我选择的项目而改变。

我找到了一些基于按钮单击事件更改颜色(方案)的解决方案。 有没有办法根据下拉列表选择触发背景颜色变化?

谢谢

【问题讨论】:

    标签: angular typescript button dynamic background


    【解决方案1】:

    您可以使用此代码触发每次更改所选项目时更改按钮颜色的功能:

      <mat-select (selectionChange)="setButtonColor($event.value)"
                  name="color" formControlName="type" >
           <mat-option *ngFor="let color of colors" 
                       [value]="color">{{type}}
            </mat-option>
       </mat-select>
    
       <button mat-button [ngStyle]="{'background-color':bgColor}">
          Button
       </button>
    

    你的 Typescript 文件应该包含一个变量 bgColor 来保存选择的值字符串和改变这个变量值的 setButtonColor 函数

    bgColor = 'blue'; // blue is the default color in this case
    
    setButtonColor(color){
        bgColor = color;
    }
    
    

    【讨论】:

    • 我在
    • 让颜色:string[] = ['green', 'red', 'orange']; bgColor = '绿色'; setButtonColor(color) { bgcolor = 颜色; }
    • @JinMa 确保 setButtonColor 是公开的:public setButtonColor(color) { bgcolor = color; }
    【解决方案2】:

    Angular Mat Select Multiple selectionchange finding which option was changed

    上述问题的答案对我有所帮助。 https://stackblitz.com/edit/angular-1e9gsd-34hrwg?file=app/select-overview-example.html 我根据上面显示的代码调整了我的代码,一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多