Angular 6 - 如何在组件级别应用外部css样式表(传单)?

sup*_*fly 8 css components leaflet angular

尝试在Angular 6组件中使用Leaflet.根据css文件的链接方式,地图显示确定或搞砸了,错误的图块不按正确的顺序排列,这意味着不考虑css.

我设法使用2个解决方案将css链接到应用程序级别(全局),但不仅仅是组件.这是我尝试过的(除了阅读有关css/leaflet/Angular的几篇文章):

工作 - 全球一级:

// styles.css
@import url("assets/lib/leaflet/leaflet.css");
Run Code Online (Sandbox Code Playgroud)

工作 - 全球一级:

// index.html
<link rel="stylesheet" href="./assets/lib/leaflet/leaflet.css" type="text/css">
Run Code Online (Sandbox Code Playgroud)

没用 - 全球一级:

// angular.json
"styles": [
    "src/styles.css",
    "src/assets/lib/leaflet/leaflet.css"
],
Run Code Online (Sandbox Code Playgroud)

没用 - 组件级别:

// ...

import * as L from "../assets/lib/leaflet/leaflet.js";
import "../assets/lib/leaflet/leaflet-bing-layer.js";
import { BingHelper } from "../assets/lib/bing/bing-helper.js";

// -> importing the .css file here does not work

@Component({
    templateUrl: "./map.component.html",
    selector: "app-map",
    styleUrls: ["../assets/lib/leaflet/leaflet.css"] // -> does not work

    // -> also tried to put the content of the .css in style: "", did not work neither

})
export class MapComponent implements AfterViewInit {
    ngAfterViewInit() {
        var map = L.map("map", {
            attributionControl: false,
            zoom: 8,
            minZoom: 3,
            maxZoom: 15,
            center: new L.LatLng(40.737, -73.923)
        });
        // ...
Run Code Online (Sandbox Code Playgroud)

无法工作:封装 - 组件级别:将 外部CSS样式加载到Angular 2 Component中

从CDN而不是本地文件加载不会更改问题.

注意:我正在使用Bing层扩展,但这对此问题没有影响.我也有使用Mapbox磁贴的相同问题.

问题:有没有办法在组件中链接Leaflet css并使其仅对组件可用,而不是整个Angular应用程序?

谢谢!

sup*_*fly 12

好的,这是有效的(感谢@Palsri,我再次阅读博客文章和Angular样式指南,并尝试了以下,这有效):

在单独的css文件中,导入传单css:

// map.component.css
@import url("../assets/lib/leaflet/leaflet.css");

.mapstyle {
    width: 100%;
    height:100%;
};
Run Code Online (Sandbox Code Playgroud)

然后在组件中,引用此css而不是传单css,如下所示:

@Component({
    templateUrl: "./map.component.html",
    selector: "app-map",
    styleUrls: ["./map.component.css"],
    encapsulation: ViewEncapsulation.None
})
Run Code Online (Sandbox Code Playgroud)

这是html模板中的代码:

<div id="map" class="mapstyle"></div>
Run Code Online (Sandbox Code Playgroud)

还有一件事:要使高度%工作,你需要定义父项大小,我目前在index.html中做了如下:

<style>
html, body {
    min-height: 100% !important;
    height:     100%;
    padding: 0px 0px 0px 0px;
    margin:  0px 0px 0px 0px;
}
</style>
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.