Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 and LeafLet Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

I have a project in Angular 2 with Leaflet, I would like to call the simple function by clicking the button, but I get

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

Here is my code. Everything works, but the function not.

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);
}
  });

Could you please help me with workaround?

like image 567
Anna F Avatar asked Nov 19 '17 21:11

Anna F


3 Answers

Do not use onclick as it's an HTML and the function you assign to onclick will be searched in global scope of javascript i-e inside <script> tags and this is no more the part of Angular2. So what you should try is something like below

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");
  }
}

And then

let popUp = (this.myData[i])['displayName'] +
'<br/><dynamic-button></dynamic-button>';
like image 59
Muhammad Usman Avatar answered Sep 21 '22 11:09

Muhammad Usman


in angular2 you will bind the event like this:

let popUp = (this.myData[i])['displayName'] +
    '<br/><button (click)="test">Raumplan</button>';

OR this:

let popUp = (this.myData[i])['displayName'] +
    '<br/><button on-click="test">Raumplan</button>';
like image 25
Abid Nawaz Avatar answered Sep 22 '22 11:09

Abid Nawaz


You can try using (click)="OpenList()"

<button (click)="OpenList()" type="button" class="btn-link btn-anchor">List</button>

Typescript function

OpenList()
 { 
 
 }
like image 21
R15 Avatar answered Sep 18 '22 11:09

R15