javascript - 在角度 9 中创建具有动态 styleUrls 的组件
问题描述
我想做一个组件,在另一个组件中多次使用,由于这个组件的模板和逻辑总是一样的,样式也不一样,所以我决定创建一个组件而不是创建多个组件,只是动态定义样式文件。
有一个在运行时称为延迟加载 CSS 的常用方法,我将包含一个链接,但问题是这种方法是全局添加 css 文件,并且由于所有 css 文件都有相同名称的类,因此 DOM 中的最后一个文件添加了效果所有组件(即此方法中未使用封装),因此此方法无效。
https://egghead.io/lessons/angular-lazy-load-css-at-runtime-with-the-angular-cli
最后我在下面放了一张图片,清楚地显示了我想要做什么。
player.component.ts:
@Component({
selector: 'app-player',
templateUrl: './player.component.html',
styleUrls: ['./player-' + number + '.css']
})
export class PlayerComponent implements OnInit {
@Input() number: number;
constructor() {}
ngOnInit(): void {}
}
player.component.html:
<p class="title">player works!</p>
播放器 1.css:
.title {
color: red;
}
播放器 2.css:
.title {
color: orange;
}
game.component.html:
<div>
<app-player [number]="1"></app-player>
<app-player [number]="2"></app-player>
<app-player [number]="3"></app-player>
</div>
如何才能做到这一点?任何解决方案表示赞赏。
谢谢。
解决方案
如果您只想动态更改颜色、字体大小等。您应该重新考虑使用全局主题。
而如果存在主要的布局差异,您有几个选择:
- 创建一个基础组件类
- 包含所有逻辑
- 使用不同的样式文件从此组件派生您的其他组件。
上述解决方案的好处是您还可以为子组件使用适当的命名,这将使代码/指令更具可读性。而不是使用数字 1、2、3,您将拥有 darkListComponent、lightListComponent 等。
使用 ngClass:
<div [ngClass]="'my-component-style-' + number"></div>
- 您仍然可以通过将样式表传递给 component.ts 文件中的 styleUrls 来分隔样式表。(
styleUrls: ['theme1.scss','theme2.scss']
) - 或者,您可以在一个文件中声明所有类,以获得最大的样式可重用性。
my-component-style-1,my-component-style-2 { ...same styling }, my-component-style-2 { color: orange; }
选项 2 更接近您的选项,您只需更新模板和样式表即可使用。
推荐阅读
- android - 一加手机是否允许从后台开始蓝牙扫描
- machine-learning - 我可以在 sklearn 中获取自定义记分器功能的额外信息吗?
- postgresql - 在全文搜索中按排名排序的正确方法?
- javascript - 异步遍历任务树
- angular - 如何使用 ng2-charts 创建自定义条形样式?
- javascript - 如何将 .json 文档中的样式属性导入反应组件?
- python - Cython 与 C 接口
- java - 如何使用 Volley for Android 存储来自 REST API 的数据
- r - 有没有办法在 R(Phyr 和 MuMin 包)中挖掘 PGLMM_compare 模型?
- xcode - 注意:不是问题——而是让 Homebrew 在 MackBook Big Sur 和更高版本上工作