css - 无法在 Angular 中选择绑定(bind)属性

标签 css angular css-selectors

我有一个 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/

相关文章:

Internet Explorer 9 中的 CSS 问题

jquery - 我的第二个 "open"按钮在单击 jQuery 时没有响应

angular - 以编程方式设置 <mat-select> 的值

typescript - 根据类名 : string 创建类的实例

CSS :nth-child(x+x):nth-child(x+x) and margins

html - 左对齐系列文本框和段落

css - Font Awesome 5 在使用 JS+SVG 版本时显示空方 block

javascript - ionic /Angular 等待服务准备好

css - Last child 或 last-type-of 伪类不起作用,为什么?

CSS div 类选择