javascript-Angular 2和LeafLet Uncaught ReferenceError:在HTMLButtonElement.onclick中未定义

我在Angular 2中有一个使用Leaflet的项目,我想通过单击按钮来调用简单函数,但是我得到了

ReferenceError: <function> is not defined at HTMLButtonElement.onclick

这是我的代码.一切正常,但功能无效.

export class MapComponent implements OnInit {

//layer
  googleStreets = L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',{
    maxZoom: 30,
    subdomains:['mt0','mt1','mt2','mt3']
  });
//!!!The FUNCTION
  test() {
    console.log('test');
  }
constructor () {}

ngOnInit() {
  this.ParseService.getJ().subscribe(data => {
    this.myData = JSON.parse(data);

//set markers and popUps
for(let i = 0; i < this.myData.length; i++) {
  let lat =+((this.myData[i])['lat']);
  let lng =+((this.myData[i])['lng']);
  this.id = (this.myData[i])['code'];

//HERE IS THE PROBLEM. BUTTON APPEARS BUT FUNCTION IS NOT AVAILABLE 
      let popUp = (this.myData[i])['displayName'] +
        '<br/><button onclick="test">Raumplan</button>';

  let markerLocation = L.latLng(lat, lng);
  let marker =  new L.Marker(markerLocation, {icon: customIcon});
  map.addLayer(marker);
  marker.bindPopup(popUp);
}
  });

您能帮我解决问题吗?

解决方法:

不要使用onclick,因为它是HTML,并且您分配给onclick的函数将在< script>中的javascript i-e的全局范围内进行搜索.标签,这不再是Angular2的一部分.所以您应该尝试的是下面的内容

import {Component} from '@angular/core';
@Component({
selector: 'dynamic-button',
template: '<button type="button" (click)="test()">Raumplan</button>'
})

export class DynamicButton{
public test(): void{
alert("Hi. I am a test call");
  }
}

接着

let popUp = (this.myData[i])['displayName'] +
'<br/><dynamic-button></dynamic-button>';
上一篇:javascript-Leaflet.js快速入门基本示例演示


下一篇:leaflet 使用GEOJSON创建矢量图形