首页 > 解决方案 > 动态 CSS 加载

问题描述

我有 2 种样式 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)'>

标签: cssangular

解决方案


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

指示

@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);
  }
}

组件.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);

}

组件.html

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

推荐阅读