【问题标题】:How to use typescript variables in css files?如何在 css 文件中使用 typescript 变量?
【发布时间】:2022-01-11 06:16:48
【问题描述】:

我正在使用 Angular,我的目标是能够在 CSS 文件中使用 typescript 中声明的字符串。我正在尝试设置导航栏组件的背景图像。稍后,将从数据库服务接收背景图像路径,这就是我需要它在打字稿文件中的原因。我读过一些关于使用[ngStyle] 的内容,但不会更新img,我只需要从数据库接收路径。我还应该尝试使用它吗?如何?我有点迷茫。

我的打字稿文件有类似的东西:

// ...
export class NavbarComponent{

background_url='../../../assets/img/background.png';

  constructor() { }
// ...

在我的 CSS 文件中,我想做类似的事情:

nav{
  background-image: background_url;
}

但是,这对我不起作用。

我怎样才能更好地解决这个问题?谢谢

【问题讨论】:

    标签: css angular typescript background-image


    【解决方案1】:

    我认为不可能从 CSS 文件中访问 ts 文件变量,但您可以从 DOM 获取元素并从 ts 文件中设置样式。

    一个例子:

    document.getElementById('element').style.backgroundImage = background_url;
    

    如果你使用像 angular 这样的框架,你可以使用 @ViewChild 从 DOM 中获取元素并使用 renderer2 库来设置它们的样式,如下所示:

    export class NavbarComponent { 
       @ViewChild('element') element: ElementRef;
       background_url='../../../assets/img/background.png';
       
       constructor(private renderer: Renderer2) {}
    
       setStyle() {
           this.renderer.setStyle(
               this.element.nativeElement,
               'background-image',
               this.background_url
           );
       }
    }
    

    然后在任何你想要的地方调用 setStyle 函数。
    更多来自 renderer2:https://angular.io/api/core/Renderer2

    【讨论】:

      猜你喜欢
      • 2015-09-21
      • 2019-06-18
      • 2019-02-09
      • 2021-02-19
      • 2021-10-19
      • 2011-08-28
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      相关资源
      最近更新 更多