2017-07-02 35 views
0

我想在我的動態window.component中多次使用map.component在不同的窗口中(我通過點擊事件獲取多個動態窗口相同的應用)。使用動態ID注入組件多種用法-Angular4

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或完全不同的解決方案? 謝謝!

回答

1

你是對的,你需要一個動態的使用,一個動態的地圖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方式數據綁定在角...