简体   繁体   English

Angular [ngStyle] 或 [style.background-color] 不适用于 '!important'

[英]Angular [ngStyle] or [style.background-color] not working with '!important'

In both situations, using '!important' it doesn't work as expected.在这两种情况下,使用 '!important' 都不会按预期工作。 If I remove the '!important', the background-color receives the change but it doesn't change cause of inheritance.如果我删除 '!important',背景颜色会收到更改,但不会更改继承的原因。 But I want it to be '!important!'.但我希望它是“!重要的!”。

without '!important':没有“!重要”:

element.style {
    margin-right: 5px;
    *background-color: 'green';* (line-through)
}

with '!important':使用“!重要”:

element.style {
    margin-right: 5px;
}

I have already tryed:我已经尝试过:

[ngStyle]="{'background-color': myColor + ' !important'}"

and

[attr.style]="'background-color: ' + myColor  + ' !important'"

and

[style.background-color]="myColor  + '!important'"

The problem is that I'm generating buttons dynamically and during the generation I want to apply the background-color.问题是我正在动态生成按钮,并且在生成期间我想应用背景颜色。 That wya I can't use @ViewChild我不能使用@ViewChild

  1. [ngStyle] not works with !important . [ngStyle]不适用于!important Instead of using ngStyle , you can implement it using [ngClass] .您可以使用[ngClass]来实现它,而不是使用ngStyle

  2. To set values to [attr.style] , you need to make the style value to TrustStyle as follows.要将值设置为[attr.style] ,您需要将样式值设置为TrustStyle ,如下所示。

[attr.style]="('font-size:' + actions.fontSize + '% !important') | safeStyle"

Here is the safeStyle pipe content.这是safeStyle管道内容。

@Pipe({ name: 'safeStyle' })
export class SafeStylePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {
  }
  transform(value) {
    return this.sanitizer.bypassSecurityTrustStyle(value);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM