【问题标题】:Dynamic CSS loading动态 CSS 加载
【发布时间】:2020-04-24 15:32:41
【问题描述】:

我有两种风格 Style1.scss 和 Style2.scss

样式1

@import "~bootstrap/dist/css/bootstrap.css";

@import "assets/css/aos/styles.css";
@import "assets/css/aos/aos.css";

@import "assets/css/layout.css";
@import "assets/css/theme-brand-1.css";

一些css文件和一个主题文件

风格2

一些 css 文件和一个主题文件,如样式 1

主题文件不同。

基于 url 参数,例如 http:\\localhost:4000\login?section=x 我需要加载样式 1,其他 http:\\localhost:4000\login?section=y 需要加载样式 2。

方法 1 - 无效

组件

this._activatedRoute.queryParams.subscribe(params => {
    this.param1 = params.brand;
    switch(params.brand){
      case 'x': this.cssUrl = '/src/styles1.scss';
      break;
      case 'y': this.cssUrl = '/src/styles2.scss';
      break;
    }
});

HTML

<link rel="stylesheet" type="text/html" [href]='sanitizer.bypassSecurityTrustResourceUrl(cssUrl)'>

【问题讨论】:

  • hii @Akshaya,你的问题是什么?你得到一个错误还是什么?我觉得还可以
  • 没有错误,href 得到正确的值但它没有加载。angular.json 中的 css 正在工作,无论我添加什么都不起作用。 @kushalshah
  • 看看这个链接shekhargulati.com/2018/01/16/…我觉得和你做的一样
  • 这个我已经完成但没有工作
  • 该链接仅适用于 .css(并且它们需要位于“资产/文件夹”中)。我认为唯一的方法是“编译”你的style1.scss 和style2.scss。您可以尝试的另一件事是“添加”您的 .scss,例如.content1 和 .content2 并在 Angular 应用程序中包含两个 .scss,在 [ngClass]="'content1'" 或 [ngClass]="content2" 成功后

标签: css angular


【解决方案1】:

使用指令动态创建规范链接并将链接移动到指令加载中的头部声明

指令

@Directive({
  selector: '[appMoveToHead]'
})
export class MoveToHeadDirective implements OnDestroy, OnInit {

  constructor(private renderer: Renderer2, 
              private elRef: ElementRef, 
              @Inject(DOCUMENT) private document: Document) {

  }

ngOnInit(): void {
    this.renderer.appendChild(this.document.head, this.elRef.nativeElement);
    this.renderer.removeAttribute(this.elRef.nativeElement, 'appmovetohead');
  }

  ngOnDestroy(): void {
    this.renderer.removeChild(this.document.head, this.elRef.nativeElement);
  }
}

component.ts

canonicalLink:string;
constructor(private sanitizer: DomSanitizer) { }
//In oninit or when your data is ready, generate canonical link
ngOnInit() {

       let canLink = "styles1.scss"; // set style here based on your condition
       // You can use pipe for sanitizing but lets do it here
       this.canonicalLink = this.sanitizer.bypassSecurityTrustResourceUrl(canLink);

}

component.html

<div *ngIf="canonicalLink">
  <link  rel="canonical" appMoveToHead [attr.href]="canonicalLink" />
</div>

【讨论】:

    猜你喜欢
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 2023-02-23
    • 2020-12-22
    • 2010-10-19
    • 2019-03-16
    • 1970-01-01
    相关资源
    最近更新 更多