【问题标题】:Switching between two styles for the same component在同一组件的两种样式之间切换
【发布时间】:2018-12-21 13:40:36
【问题描述】:

我正在尝试在我的 Angular 应用程序中包含两个样式 URL,

我尝试了其他几个类似的问题,但答案对我不起作用。我不知道如何解决。

我想要实现的是根据if条件在两种样式之间切换

我为什么要这样做:这是因为应用程序应该支持两种语言,这需要 RTL 和 LTR 样式文件用于同一组件,,

这样的问题可以处理吗??

【问题讨论】:

    标签: angular angular5 angular2-template angular6


    【解决方案1】:

    为 .html 中的 [class] 指定一些函数

    <span [class]="getStyleClass()">ABCD</span>
    

    然后在你的 .ts 中为你的 getStyleClass() 添加一些逻辑

    getStyleClass() {
        return this.value > this.anotherValue?"classOne":"classTwo";
      }
    

    【讨论】:

    • 非常感谢,但这是针对一个元素,是否可以更改整个样式 URL,因为整个样式应根据属性值更改
    • 然后你可以尝试像这里一样动态添加样式表:stackoverflow.com/questions/42496999/…
    • 试图添加样式,因为它说这就是我得到的
    • 拒绝应用来自 'localhost:4200/nav.component.scss' 的样式,因为它的 MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。
    • 这是我在 ts 文件中添加的 addStyleSheet() { var headID = document.getElementsByTagName('head')[0]; var link = document.createElement('link'); link.type = '文本/css'; link.rel = '样式表'; link.id = 'widget_styles'; headID.appendChild(链接); link.href = 'nav.component.scss'; } 构造函数() { } ngOnInit() { this.addStyleSheet() }
    【解决方案2】:

    有 2 个 css 文件:src/assets/style1.css 和 src/assets/style2.css

    第 1 步添加一个带有 ID 的链接位于 index.html 文件的头部

    <html>
      <head>
        <link href="" id="mycss" rel="stylesheet">
      </head>
      <body>
        <my-app></my-app>
    </body>
    </html>
    

    第 2 步:使用以下 typescript 并使用您自己想要的逻辑进行修改

    import { Component, Inject } from '@angular/core';
     import { DOCUMENT } from '@angular/platform-browser';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      files = ["assets/style1.css","assets/style2.css"]
    
      constructor(@Inject(DOCUMENT) private document) {}
    
      toggle() {
    
        var oldlink = this.document.getElementById("mycss");
    
        var newlink = this.document.createElement("link");
        newlink.setAttribute("rel", "stylesheet");
        newlink.setAttribute("type", "text/css");
        newlink.setAttribute("href", this.files[1]);
    
        this.document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      • 2015-08-09
      • 2021-10-12
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多