首页 > 解决方案 > Angular如何从服务器加载css

问题描述

我想尝试从服务器/外部源介绍角度加载 css。我已经在尝试使用 DomSanitizer 但没有成功。样式表显示在 chrome 的网络选项卡内,但 html 不应用样式表。

铬网络选项卡:

在 TS 文件中:

import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {DomSanitizer} from "@angular/platform-browser";

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.None,
})
export class AppComponent implements OnInit{
title = 'angulardynamicss';
cssUrl = 'http://localhost:8080/api/csspoc/asFile'

constructor(public sanitizer: DomSanitizer) {}

ngOnInit(): void {}

}

HTML 看起来像:

<link rel="stylesheet" [href]='sanitizer.bypassSecurityTrustResourceUrl("http://localhost:8080/api/csspoc/asFile")'>

<p class="test">hello</p>

样式表文件包含:

.test {
    background-color: blue;
}

p{
    color:yellow;
}

标签: cssangular

解决方案


为什么要在 AppComponent 中注入呢?你不能只在你的 index.html中添加<link>标签吗?<head>


推荐阅读