gpt4 book ai didi

javascript - 如何在 Angular 中添加动态外部脚本?

转载 作者:行者123 更新时间:2023-11-30 19:08:02 29 4
gpt4 key购买 nike

我有两个 angular 门户,它们都有不同的样式,所以我想在加载组件上添加样式,样式已添加但未加载。请帮我实现

这是我的代码

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

这是输出

enter image description here

感谢任何解决方案!

最佳答案

为了在您的组件之外使用任何样式,您需要将其导入到 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

关于javascript - 如何在 Angular 中添加动态外部脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58776926/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com