如何动态生成CSS类和/或设置其属性

时间:2019-04-19 17:02:32

标签: css angular

标题实际上不是一个问题,它更像是一个主意,我不知道哪种方法最适合我的情况。

所以,问题出在这里。我有一些具有复杂结构和样式的第三方组件。它的某些部分具有一些预定义的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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

不知道您是否正在使用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规则,就这样。

使用此解决方案,您可以避免出于样式目的而使用多余的wrapper元素,这是一件好事。

答案 2 :(得分:0)

我认为[ngClass]将帮助您动态地覆盖css类。有关进一步的解释,您可以参考给出的link

<div [ngClass] = “{ 'CUSTOM_CSS_CLASS': CONDITION }”></div>

<div [ngClass]="{ 'CUSTOM_CSS_CLASS': CONDITION, 'OTHER_CLASS': !CONDITION }"></div>