【问题标题】:How to dynamically generate CSS class and/or set its property如何动态生成 CSS 类和/或设置其属性
【发布时间】:2019-09-09 22:13:23
【问题描述】:

标题并不是一个真正的问题,它更像是一个想法,我不知道哪种方法最适合我的情况。

所以,问题。我有一些具有复杂结构和样式的第 3 方组件。它的某些部分有一些预定义的 CSS 类,我可以在周围的组件中用 CSS 覆盖它们。像这样的:

我的组件:

<div class="my-cmp-container">
    <some-3rd-party-cmp></some-3rd-party-cmp>
</div>

第三方组件:

<div class="3rd-party-css-class">
    ...
</div>

例如,3rd-party-css-class 具有样式background-color: #f00,我可以用.my-cmp-container .3rd-party-css-class { background-color: #fff; } 等覆盖它。但是。如果我需要动态设置颜色怎么办,例如它存储在数据库中,我无法在我的类的 CSS 中预定义每个案例。我只有十六进制的颜色。

理论上,我可以为some-3rd-party-cmp 的每个实例生成唯一的字符串以设置为 CSS 类,并以某种方式在我的组件中生成 CSS?我有点迷茫,最好的方法是什么?

编辑:代码示例说明情况https://stackblitz.com/edit/angular-kxdatq

【问题讨论】:

  • 第 3 方组件不使样式属性可用于数据绑定?
  • @ConnorsFan 当然不是,否则就没有问题了。 :)
  • 我在stackblitz上添加了代码示例来说明情况

标签: css angular


【解决方案1】:

您正在尝试做的是this open issue 关于Angular 中的样式表绑定的主题。在该功能可用之前,您可以使用自定义指令获得所需的内容。这是一个指令,它检索由ng-zorro-antd 生成的复选框元素并对其应用两个颜色属性。这两种颜色是@Input 属性,该指令实现了OnChanges,它允许对属性绑定更改做出反应。

@Directive({
  selector: "[nz-checkbox][nz-chk-style]"
})
export class CheckBoxStyleDirective implements OnInit, OnChanges {

  @Input("nz-chk-bkgnd") chkBkgndColor: string;
  @Input("nz-chk-border") chkBorderColor: string;

  private checkbox: HTMLElement;

  constructor(private renderer: Renderer2, private el: ElementRef) { }

  ngOnInit() {
    this.checkbox = this.el.nativeElement.querySelector(".ant-checkbox-inner");
    this.updateBackgroundColor();
    this.updateBorderColor();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.chkBkgndColor) {
      this.updateBackgroundColor();
    }
    if (changes.chkBorderColor) {
      this.updateBorderColor();
    }
  }

  updateBackgroundColor() {
    if (this.checkbox) {
      this.renderer.setStyle(this.checkbox, "background-color", this.chkBkgndColor);
    }
  }

  updateBorderColor() {
    if (this.checkbox) {
      this.renderer.setStyle(this.checkbox, "border-color", this.chkBorderColor);
    }
  }
}

一旦指令属性选择器nz-chk-style 应用于第三方元素,您可以通过属性绑定设置复选框背景和边框颜色,如下所示:

<span nz-checkbox nz-chk-style [nz-chk-bkgnd]="bkgndColor" [nz-chk-border]="borderColor" >

请参阅this interactive stackblitz 以获取演示。

【讨论】:

  • 与原始复选框的行为不同,但我知道了。谢谢,这比更改 css 属性要好得多。
【解决方案2】:

不确定你是否使用了 Angular,但你标记了它,所以我猜你是。

如果您只想更改颜色而不是其他任何内容,而不是使用 .3rd-party-css-class 类,您可以像这样使用 ng 样式:

<some-3rd-party-cmp ng-style="{ color: your_color_hex_variable }"></some-3rd-party-cmp>

如果样式,您还可以定义整个对象并传递它。

您还可以使用 ng-class 并传递一个或一组类名,您想在组件上添加额外的内容:

<some-3rd-party-cmp ng-class="[cls1, cls2, cls3]"></some-3rd-party-cmp>

<some-3rd-party-cmp ng-class="[3rd-party-css-class, someCondition ? 'another-class-name' : '']"></some-3rd-party-cmp>

在类中你可以定义你想要应用的css规则,就是这样。

使用此解决方案,您可以避免使用额外的包装元素来进行样式设置,这是一件好事。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多