gui*_*cgs 7 angular-material angular
我需要动态更改角度材质进度条的颜色。我意识到这并不是那么简单,那么最好的方法是什么呢?
要求:
相关链接:(1)
更新:
避免使用deep, TL; DR:Deep在技术上是无效的(例如,deeprecated:p)
有关更多信息,请参考:在Angular 2中使用/ deep /和>>>
现在,要更改垫进度条的颜色,
转到您的styles.scss文件(或项目中的主要css / scss文件)
添加此类->
.green-progress .mat-progress-bar-fill::after {
background-color: green !important;
}
Run Code Online (Sandbox Code Playgroud)
您的mat-progress应该使用上述类,例如->
<mat-progress-bar class="green-progress" mode="indeterminate"></mat-progress-bar>
Run Code Online (Sandbox Code Playgroud)
我们可以创建一个属性指令,该指令接受颜色值并<mat-progress-bar>为我们覆盖默认样式。
这是一个工作演示:https : //stackblitz.com/edit/material-progress-bar-color-directive
这里是一个简短的解释:
如果我们检查<mat-progress-bar>开发人员工具。我们会发现进度条的颜色是在::after伪元素中定义的,就像这样。
.mat-progress-bar-fill::after {
background-color: #3f51b5;
}
Run Code Online (Sandbox Code Playgroud)
并且我们已经知道,不可能使用DOM querySelector()方法直接操作伪元素。但是我们可以添加新样式,这些样式也可以具有伪元素规则。请查看此线程以获取更多详细信息。/sf/answers/1519687011/
因此,我们可以制定一条可以为我们添加新样式的指令。
import { Directive, Input, OnChanges, SimpleChanges, ElementRef } from '@angular/core';
@Directive({
selector: '[appProgressBarColor]'
})
export class ProgressBarColor implements OnChanges{
static counter = 0;
@Input() appProgressBarColor;
styleEl:HTMLStyleElement = document.createElement('style');
//generate unique attribule which we will use to minimise the scope of our dynamic style
uniqueAttr = `app-progress-bar-color-${ProgressBarColor.counter++}`;
constructor(private el: ElementRef) {
const nativeEl: HTMLElement = this.el.nativeElement;
nativeEl.setAttribute(this.uniqueAttr,'');
nativeEl.appendChild(this.styleEl);
}
ngOnChanges(changes: SimpleChanges): void{
this.updateColor();
}
updateColor(): void{
// update dynamic style with the uniqueAttr
this.styleEl.innerText = `
[${this.uniqueAttr}] .mat-progress-bar-fill::after {
background-color: ${this.appProgressBarColor};
}
`;
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我们在这里所做的只是创建一个新的HtmlStyleElement并将其添加到host元素内。
在内部updateColor()方法中,我们正在更新innerText附加的样式标签。请注意,我们在此处使用具有唯一属性的属性选择器,以将样式范围最小化,仅适用于宿主。因为我们只想覆盖应用了指令的进度条的样式。
您可以像这样在模板中使用此指令。
<mat-progress-bar [appProgressBarColor]="'orange'"
mode="determinate"
value="40"></mat-progress-bar>
Run Code Online (Sandbox Code Playgroud)
我希望这将有所帮助。
| 归档时间: |
|
| 查看次数: |
2483 次 |
| 最近记录: |