我正在尝试使用以下代码为跨度提供一些背景颜色和文本颜色:
element.component.html:
<span
[title]="element.name"
class="badge badge-pill"
[ngStyle]="setBadgeStyles()"
>
hello there
</span>
element.component.ts:
import { Component, OnInit, Input } from "@angular/core";
@Component({
selector: "app-element",
templateUrl: "./element.component.html",
styleUrls: ["./element.component.css"],
})
export class ElementComponent implements OnInit {
@Input()
element: Element;
@Input()
hexColor: string;
constructor() {}
ngOnInit(): void {}
getHexCode(): string {
return `#${this.element.hexColor}`;
}
setBadgeStyles() {
return {
"background-color": this.getHexCode(),
color: this.getHexCode(),
};
}
}
样式根本没有被应用。我还尝试了以下方法:
<span
[title]="element.name"
[style.color]="'getHexCode()'"
[style.background-color]="'getHexCode()'"
class="badge badge-pill"
>
Hello there
</span>
Yet again, it does not work.
The peculiar thing is that the color DOES change when I replace getHexCode()
with red
in the latest example.
Furthermore, I have also tried to remove the '
from the style binding values...
有人能启发我做错什么吗?
尝试从setBadgeStyles方法返回css作为字符串。
这是一个示例,它看起来像不使用方法来获得样式的样子:
如果这样不起作用(可能知道如何自动进行转换),也请尝试对两个CSS属性都使用''。就像是: