【问题标题】:How to add different css files conditionally on angular 2 component?如何在 Angular 2 组件上有条件地添加不同的 css 文件?
【发布时间】:2018-06-29 11:03:00
【问题描述】:

我的应用使用不同的语言,其中一些是从右到左的。我有两个单独的 css 文件;一个用于 LTR,另一个用于 RTL。

如何有条件地在组件上添加 css 文件?

我找到了解决这个问题的方法(参考github issue上的答案),但这不是一个好的解决方案。

正如您将在下面看到的,我解决此问题的代码在这里。

app.component.ts

@Component({
  selector: 'ngw-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  isRtl:Boolean;

  constructor(@Inject(LOCALE_ID) localeId) {
    if(localeId == "fa-IR") {
      require('style-loader!./app.component.rtl.css');
    }
  }

  ngOnInit() {}
}

typings.d.ts

declare var require: any;

我在寻找什么:

主题.ts

interface Theme {
  url: string;
  rel: string;
  media: string;
}

app.component.ts

@Component({
  selector: 'ngw-root',
  templateUrl: './app.component.html',
  styleUrls: AppComponentThemeProvider
})
export class AppComponent implements OnInit {
  constructor() {
  }

  ngOnInit() {}
}

app.component.theme.ts

export class AppComponentThemeProvider {
  constructor(@Inject(LOCALE_ID) private localeId) {
  }

  getThemes() {
    let themes = [<Theme>{url:'./app.component.css'}];

    if(this.localeId == 'fa-IR') {
      themes.push(<Theme>{url: './app.component.rtl.css'})
    }

    return themes;
  }
}

【问题讨论】:

  • 在帖子中添加更多信息

标签: angular


【解决方案1】:

据我所知,这在 Angular 中并不容易实现,而且浏览器的行为方式是,一旦您下载 CSS,它们就会一直存在,直到您关闭浏览器或删除样式,这很棘手。

最简单和最安全的选择是将 css 文件命名为命名空间,并有条件地将该命名空间添加到您的正文中。

LTR 样式:

 app-root.LTR{
    all your LTR styles will be here
 }

RTL 样式:

  app-root.RTL{
    all your RTL styles will be here
 }

然后在你的app-root 组件中:

@Component({
    selector:'app-root'

})

export class AppComponent{

      @HostBinding('[class.RTL]') get language(){


      if  it should be RTL   return true;

     }

      @HostBinding('[class.LTR]') get language(){


         if  it should be LTR   return true;

     }


// I'm not sure how would you determine which language is it gonna be, but it's normally a parameter in the url , so you can use Angular's router to detect that and flesh out the above if conditions

}

【讨论】:

    猜你喜欢
    • 2017-07-18
    • 2018-05-14
    • 2017-09-11
    • 2021-12-22
    • 2016-06-05
    • 2018-10-03
    • 2016-09-26
    • 2017-02-02
    • 2021-12-22
    相关资源
    最近更新 更多