Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
Call a typescript method from html written inside typescript component

I have a pop-up with 2 buttons, Update and Delete. When the Update button is pressed, I want to make the initial pop-up disappear and a new pop-up appear populated with the same fields but editable with another 2 buttons at the bottom, Confirm and Delete.

I want to configure the code for the Update pop-up in a separate method and call it from the HTML button when the Update button is pressed

How do I call the desired method (myFunction) from the HTML written inside the TypeScript Component at the button component?

 private initMap(): void {
    this.map = L.map('map', {
      center: this.centroid,
      zoom: 2.8
    });

    this.tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', 
    {
      minZoom: 2.8,
      attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
    });

    this.tiles.addTo(this.map);
    
    this.powerPlantService.getAll().subscribe((data: any)=>{
      console.log(data);
      this.geoJsonFeature = data;
      
      L.geoJSON(data, {onEachFeature: myOnEachFeatureMethod}).addTo(this.map)

    }) 

    function myOnEachFeatureMethod(feature:any, layer:L.GeoJSON)
    {
      
        layer.bindPopup(
          "Power Plant Id: " + feature.properties.xxx +
          "<br>Power Plant Name: " + feature.properties.xxxx +
          '<div style="text-align:center"> '+

          //below in the button i want to call the myFunction method. How do I do that?
          '<br><button type="button" class="btn btn-primary" style="margin-right: 5px" data = "' + feature.properties.xxx + '" ' + '>Update</button>' + 

          '<button type="button" class="btn btn-danger" style="margin-left: 5px" data = "' + feature.properties.xxxx + '" ' + '>Delete</button>'   +
          '</div>'
          );  
    }  
  }  
 
  myFunction(layer: any) {
    console.log("Yeet");
    layer.bindPopup("Yeet");
  }

This is the pop-up displayed when the map pin is clicked

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In order to pass messages to the component from the button click event, we will use use normal javascript file and include it in the angular.json.

We also need rxjs declared on the window object. rxjs which is installed within Angular through npm isn't though, so we include a cdn script file in the head of the index.html file.

src/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    ....
    <script type="text/javascript" src="https://unpkg.com/rxjs@%5E7/dist/bundles/rxjs.umd.min.js"></script>
  </head>
  <body>
    <app-root></app-root>
  </body>
</html>

Create a custom.js file within the /src/assets/js folder, and create a new RxJS Subject and also declare the function you want to call. Within that function just call next on the subject to emit a new event/message.

src/assets/js/custom.js

var my_custom_subject = new rxjs.Subject()
function myFunction() {
  my_custom_subject.next('hello from custom')
}

In order the render this script within your application, you can either include it in the head tag as well or include it within the scripts array in the angular.json file. It's either the head tag or either in the configuration file, otherwise it will try to declare the my_custom_subject twice.

angular.json

{
  ...
  "projects": {
    YOUR_PROJECT_NAME: {
      "architect": {
        "build": {
          "options": {
            "scripts": [
              "src/assets/js/custom.js"
            ]
          }
        }
      }
    }
  }
}

Within your component declare a const with the same name as the subject you created in the custom.jsfile. Within the ngOnInit subscribe to the Observable to listen to the events.

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

declare const my_custom_subject: Subject<any>

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit, OnDestroy {
  private subcription: Subscription;

  ...

  ngOnInit(): void {
    this.subcription = my_custom_subject.subscribe(data => console.log('subscription', data))
  }

  ngOnDestroy(): void {
    this.subcription.unsubscribe();
  }

  ...

}

This will allow you the call myFunction declared with regular javascript which will pass a message to your component. By subscribing to it, you're actually listening to the click events.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda