css - 动态 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)'>
解决方案
使用指令动态创建规范链接并将链接移动到指令加载中的头声明
指示
@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>
推荐阅读
- php - 属性对 Sendinblue API 无效
- javascript - 需要帮助使用 vue-router 加载组件
- android - 如何在自定义视图中定义相对触摸大小?
- angular - 如何有效地将带有数据的大型 json 加载到角度 8 上的多个表中?
- javascript - React - 计算元素之间的较大值仅部分工作
- uml - 我应该使用哪种类型的图表(基础设施)?
- xml - XML 模式验证。项目数不定的无序列表
- flutter - Flutter 中如何改变 ScrollController 的偏移值?
- input - 如何在 ipython 中创建多行输入?
- list - 如何通过 Terraform 0.12 中的列表(对象)进行 for_each