首页 > 解决方案 > 在角度 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>

如何才能做到这一点?任何解决方案表示赞赏。

谢谢。

标签: javascripthtmlcssangular

解决方案


如果您只想动态更改颜色、字体大小等。您应该重新考虑使用全局主题。

而如果存在主要的布局差异,您有几个选择:

  1. 创建一个基础组件类
    • 包含所有逻辑
    • 使用不同的样式文件从此组件派生您的其他组件。

上述解决方案的好处是您还可以为子组件使用适当的命名,这将使代码/指令更具可读性。而不是使用数字 1、2、3,您将拥有 darkListComponent、lightListComponent 等。

  1. 使用 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 更接近您的选项,您只需更新模板和样式表即可使用。


推荐阅读