繁体   English   中英

注入具有动态ID的组件以用于多种用途-Angular4

[英]Inject components with dynamic id for multiple usage -Angular4

我想在不同的窗口中多次使用我的dynamic window.component中的map.component(我在同一应用程序中通过点击事件在其中获得多个带有地图的动态窗口)。

window.component.html

<jqxWindow>
    <div>
        <olmap></olmap>
    </div>
<jqxWindow>

map.component.html

<div id="map" class="map" ></div>

map.component.ts

import { Component, OnInit } from '@angular/core';

import * as ol from 'openlayers';

@Component({
  selector: 'olmap',
  templateUrl: './map.component.html',
  // template: '<div id={{mapId}}></div>',
  styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {

  mapId: string = "";
  map: ol.Map = undefined;

  constructor() {
    this.mapId = "map";
  }

  ngOnInit() {

    this.map = new ol.Map({
      target: "map",
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM()
        })
      ],
      view: new ol.View({
        center: ol.proj.fromLonLat([37.41, 8.82]),
        zoom: 4
      })
    });
  }
}

但是只有在第一个窗口中才会渲染地图。 第二,第三,...窗口为空。 也许我需要为每个窗口提供新的地图id或完全不同的解决方案? 谢谢!

没错,您需要动态使用,动态map-id。 在map.components.ts中,您可以为地图构建一个随机ID:

import { Component, OnInit } from '@angular/core';

import * as ol from 'openlayers';

@Component({
  selector: 'olmap',
  templateUrl: './map.component.html',
  // template: '<div id={{mapId}}></div>',
  styleUrls: ['./map.component.css']
})
export class MapComponent implements OnInit {

  mapId: string = "";
  map: ol.Map = undefined;

  constructor() {
    this.mapId = "map" + Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
  }

  ngOnInit() {

    this.map = new ol.Map({
      target: "map",
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM()
        })
      ],
      view: new ol.View({
        center: ol.proj.fromLonLat([37.41, 8.82]),
        zoom: 4
      })
    });
  }
}

您的map.component.html应该如下所示:

<div  id={{mapId}} class="map"></div>

您还应该检查2种角度数据绑定方式...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM