使用Angular5 - 我知道如何将HTML元素的样式绑定到布尔值,但我无法找到同时为多个样式执行此操作的解释。
即。我发现这样的东西很好用:
[style.background]="r.favourite === true ? '#3f51b5' : 'white'"
但是我也想在这一点上将文本的颜色改为白色......而且我不想用大量的[style.xxx]标签来混淆我的组件。
有没有办法可以动态绑定到CSS类,以便在r.favourite === true
时使用?
我已经看到了可以这样做的方法......但是这假设你在同一个文件中绑定:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<button class="my-btn" [class.extraclass]="someProperty">Call to Action</button>
`,
styles: [`
.my-btn { font-size:1.7em; }
.extraclass { background: black; color: white; }
`]
})
export class AppComponent {
someProperty = true;
}
但是我的CSS存储在共享文件中 - 这样我的文件结构如下:
import { Component } from '@angular/core';
@Component({
selector: 'my-component',
styleUrls: ['./css/shared-styles.css']
template: `
<button class="my-btn" [class.extraclass]="someProperty">Call to Action</button>
`
})
export class MyComponent {
someProperty = true;
}
答案 0 :(得分:1)
您可以使用NgClass。
Set markup CSV
在哪里&#39;文字成功&#39;和&#39; text-danger&#39;是你定义的类。 请参阅这篇关于NgClass和NgStyle的精彩文章: https://codecraft.tv/courses/angular/built-in-directives/ngstyle-and-ngclass/
希望这有帮助