我有一个 Angular 自定义进度条。我想为 [value]
绑定(bind)一个选择器.但是,如果我在 Angular 中绑定(bind)该属性,则无法再进行选择。
<progress-bar value="50">
作品
<progress-bar [value]="value">
失败
该属性在第二种情况下不存在,它只是作为 ng-reflect-* 属性之一存在。这是预期的行为吗?
组件:
ProgressBar {
private currentValue;
@Input() set value(value: number) { this.currentValue = value; }
get value() { return this.currentValue; }
...
}
CSS:
progress-bar {
display: block;
height: 4px;
width: 100%;
// determinate
&[value] {
background: map_get($color-palette, progress-bar-background);
.progress {
height: 100%;
background: map_get($color-palette, progress-bar-color);
animation: none;
transform-origin: top left;
transition: transform 250ms ease;
}
}
// indeterminate
&:not([value]) {
background: transparent;
}
}
最佳答案
而不是 property binding , 你可以使用 attribute binding :
<progress-bar [attr.value]="value">
export class ProgressBar {
constructor(private elementRef: ElementRef<HTMLElement>) {}
get value() {
const element = this.elementRef.nativeElement;
return element.getAttribute("value");
}
}
参见 this stackblitz用于演示。
一个更简单的解决方案是使用 HostBinding
在组件上有条件地设置一个类:
export class ProgressBar {
private currentValue;
@Input()
get value() { return this.currentValue; }
set value(value: number) { this.currentValue = value; }
@HostBinding("class.has-value") get hasValue(): boolean {
return !!this.currentValue;
}
}
并根据类选择器应用样式:
progress-bar {
...
&.has-value {
...
}
&:not(.has-value) {
...
}
}
参见 this stackblitz用于演示。
关于css - 无法在 Angular 中选择绑定(bind)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51937422/