首页 > 解决方案 > Angular 从组件内部更改 styleUrls 值

问题描述

我正在尝试允许用户在运行时更改 styleUrls 值,所以我尝试这样做:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  // styleUrls: [ './app.component.css' ]
  styleUrls: [styleUrl]

})
export class AppComponent implements OnInit  {

  styleUrl = './app.component.css'
  
  ngOnInit() {

    this.styleUrl = './another.css';

  }

}

这不起作用,所以有可能得到这样的东西吗?

如果有怎么办?

标签: angularangular12

解决方案


你想要的可以实现,但不是这样。

虽然您可以指定文件并在运行时更改它们,但使用Reflect Metada Api,这是相当先进的事情,可能会导致 Angular 出现其他问题。

如果您只想更改单个组件的样式,可以使用两个 scss 文件和一个HostBinding.

这是一个例子:

零件

@Component({
  selector: 'my-app',
  templateUrl: '<button (click)="changeStyle()">Change Style</button>',
  styleUrls: [ './app-one.component.scss', './app-two.component.scss' ]
})
export class AppComponent implements onInit {

  @HostBinding('class') css: string = undefined; 

  ngOnInit(): void {
    this.changeStyle();
  }

  changeStyle(): void {
    if (/* condition */) {
      // custom behaviour here
      this.css = 'active';
    } else {
      // custom behaviour here
      this.css = undefined;
    }
  }
}

AppOne CSS

:host.active {
  button {
    background-color: red;
  }
}

AppTwo CSS

:host:not(.active) {
  button {
    background-color: blue;
  }
}

请注意,我声明了两个 scss 文件,一个用于我想要的每种自定义 scss。我还使用HostBinding装饰器来触发激活的样式。

我不更改运行时文件,而是使用 css 特定性规则来仅应用我想要的 css。这是使用:not()伪选择器完成的,您可以在此处阅读。

我还要补充一点,虽然这是在给定组件中实现更改样式的可行方法,但如果您想要实现,还有许多其他更好的方法可以在 Angular 应用程序中实现主题等。


推荐阅读