[英]How to add Dynamic external scripts in Angular?
我在 angular 中有两个门户,并且都有不同的 styles,所以我想在加载组件上添加样式,添加了样式但未加载。 请帮我实施
这是我的代码
import { Component, OnInit, Inject } from "@angular/core";
import { DOCUMENT } from "@angular/common";
export interface type {
fileName: string;
fileType: string;
}
const externalScripts: type[] = [
{ fileName: "src/assets/blk-design-system.css", fileType: "css" },
{ fileName: "src/assets/nucleo-icons.css", fileType: "css" }
];
@Component({
selector: "app-layout",
templateUrl: "./layout.component.html",
styleUrls: ["./layout.component.css"]
})
export class LayoutComponent implements OnInit {
constructor(@Inject(DOCUMENT) private document: Document) {}
ngOnInit() {
this.loadScripts();
}
loadScripts() {
externalScripts.forEach(element => {
// this.scriptLoader.loadJsCssFiles(element.fileName, element.fileType);
this.loadStyle(element.fileName);
});
}
loadStyle(styleName: string) {
const head = this.document.getElementsByTagName("head")[0];
const style = this.document.createElement("link");
style.id = "client-theme";
style.rel = "stylesheet";
style.href = `${styleName}`;
head.appendChild(style);
}
}
这是 Output
任何解决方案表示赞赏!
为了在组件之外使用任何样式,您需要将其导入src/styles.css
文件中。
@import "assets/blk-design-system.css";
如果您发现任何已导入的文件(如 bootstrap),只需在其下方添加导入行。
为了防止封装在组件中:
@Component({
selector: "app-layout",
templateUrl: "./layout.component.html",
styleUrls: [
"./layout.component.css",
//include external css here
],
encapsulation: ViewEncapsulation.None,
})
并在 styleUrls 中包含外部 css
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.