Azure Maps HTML 标记忽略 Angular 中的 CSS

Azure Maps HTML Marker ignoring CSS in Angular

我目前正在使用 Azure Maps 开发一个 Angular 11+ 项目。我想创建一个自定义 CSS 样式的 HTML 标记,如文档中所示 (https://docs.microsoft.com/en-us/azure/azure-maps/map-add-custom-html),但 Angular 似乎完全忽略了 CSS。使用 F12 我可以找到标记,但我无法在视觉上看到它。如果我使用内联 CSS 创建 HTML 标记没有问题,但我真的很想像文档中那样将两者分开。
我使用 npm install azure-maps-control 安装了 Azure Maps。

index.html:

<link
  rel="stylesheet"
  href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css"
  type="text/css"
/>

map.component.html:

<div id="myMap"></div>

map.component.ts:

import { Component, OnInit } from '@angular/core';
import * as atlas from 'azure-maps-control';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss'],
})
export class MapComponent implements OnInit {
      
  constructor() {}

  ngOnInit(): void {

// build the map
var map = new atlas.Map('myMap', {
  center: [10.39, 55.393],
  zoom: 12,
  showLogo: false,
  showBuildingModels: true,
  style: 'grayscale_light',
  language: 'da-DK',
  authOptions: {
    authType: atlas.AuthenticationType.subscriptionKey,
    subscriptionKey: 'key',
  },
});

// add controls like zooming, compass and pitch to the map
map.controls.add(
  [
    new atlas.control.ZoomControl(),
    new atlas.control.CompassControl(),
    new atlas.control.PitchControl(),
  ],
  { position: atlas.ControlPosition.TopRight }
);

map.events.add('ready', () => {

  var marker = new atlas.HtmlMarker({
    htmlContent: '<div class="test"></div>', // <-- this does not work
    position: [10.39, 55.393],
    pixelOffset: [5, -18],
  });

  map.markers.add(marker);

  var marker2 = new atlas.HtmlMarker({
    htmlContent:
      '<div style="background-color: blue; width: 20px; height: 50px;"></div>', // <-- this works fine
    position: [10.55, 55.393],
    pixelOffset: [5, -18],
  });

  map.markers.add(marker2);
});

}

map.component.css:

html,
body {
  margin: 0;
}

#myMap {
  height: calc(100vh - 58px);
  width: 100vw;
}

.test {
  background-color: red;
  width: 20px;
  height: 20px;
}

如何将 CSS 文件连接到此处的 HTML?如有任何建议,我们将不胜感激。

我不是 angular 专家,但查看您的 post,看起来您的样式导入中有“.scss”,并且您的文件有“ .css" 文件扩展名。

尝试将 div 添加到您的页面并为其指定相同的“测试”class 名称,以查看 CSS class 是否正在加载到页面中。

我远不是CSS专家,但我认为这与angular的视图封装有关。您正在尝试将样式应用于不属于您的组件的 DOM 个元素。

有两种可能性:

  • 将您的样式声明为全局样式。您只需要将您的风格放在 styles.scss.

styles.scss

body {
  margin: 0;
}

.test {
  background-color: red;
  width: 20px;
  height: 20px;
}

map.component.scss

#myMap {
  height: calc(100vh - 58px);
  width: 100vw;
}

:host ::ng-deep .test {
  background-color: red;
  width: 20px;
  height: 20px;
}

在这两种情况下,样式都会应用于您的 HTML 标记

希望对您有所帮助!