Creating eye-catching alerts with AngularJS 2 and dynamic templates

My small app works great without Angular templating, but now I need to incorporate it. I want Sweet Alert to pop up when a button is clicked. However, nothing happens when the button is called from the template. I suspect it might be related to event binding since the app loads the code after the DOM has initialized.

//app.component.ts

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

@Component({
  selector: 'my-app',
  template: `
    <form>
     <button type="button" class="ticket_button">Book</button>
    </form>
    `
})
export class AppComponent {
//some app logic here
}


//index.html
//I haven't included normal header stuff here, but the my-app class shows the button 

<html<body>
    <my-app class="main_ticket">Loading...</my-app>
</body></html>

// I tried using event binding from jQuery $('.main_ticket').on('change', '.ticket_button', function() {//logic here}, but it didn't work either 

<script>
 //Sweet Alert call
document.querySelector('button').onclick = function(){
  swal("Here's a message!");
};
</script>

Answer №1

You need to utilize Life Cycle Hooks in order to make it functional:

export class AppComponent implements ngAfterViewInit{
//implementing some app logic here

     ngAfterViewInit(){
       document.querySelector('button').onclick = function(){
          swal("Here's a message!");
       };
     }

}

Alternatively, you can opt for using angular2's Standard events:

@Component({
  selector: 'my-app',
  template: `
    <form>
     <button type="button" (click)="popAlert();" class="ticket_button">Book</button>
    </form>
    `
})

In the Class:

export class AppComponent {
//implementing some app logic here
    popAlert(){
      swal("Here's a message!");
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Custom close functionality for AngularJS lightbox implemented in controller

I'm looking to create a customized close controller that will not only close the lightbox when I click "OK" in the alert, but I am unsure of how to do it. Here is the link for reference: Lightbox ...

Nuxt - Issue persisting logged in state on refresh despite information being stored in local storage and cookies

I am facing an issue where the state gets cleared on refresh, even though the token, userid, user email, and expiration date are stored in local storage and cookies. I suspect there might be a problem with the store or something else needs to be done to re ...

Sort by label using the pipe operator in RxJS with Angular

I have a situation where I am using an observable in my HTML code with the async pipe. I want to sort the observable by the 'label' property, but I'm not sure how to correctly implement this sorting logic within the pipe. The labels can be e ...

Error: Unexpected character 'o' encountered in AngularJS syntax

Whenever I try to call this controller, it gives me an error. hiren.controller('hirenz' , function($scope , $http , $location , $routeParams){ $http.post((rootURL + "music") , {'alpha' : $routeParams.alpha , 'name' : $rou ...

Text appearing in varying sizes across browsers

I need some help with a coding issue I'm facing. I have a form where one of the inputs is connected to a JavaScript function that updates a div on the page as the user types. However, I want to limit the width of this div to 900px and make sure it onl ...

What is the solution for the error "Build error occurred ReferenceError: self is not defined" when building a NextJs application?

pages/components/moru-sdk.js // https://libraries.io/npm/moru-web-sdk import { MoruCheckout } from "moru-web-sdk"; function MoruService() { const options = { access_key: "test_9425294388834bdface7d1b58fd538bf67627d9408fe4f258982 ...

Adjusting Javascript code to convert numerical values in HTML table cells from thousands to millions

Does anyone know how to create a Javascript function for a web report that converts table values to thousands or millions by dividing or multiplying by 1000? The issue is that each value is clickable, meaning it is wrapped in an anchor tag. Is there a wa ...

The NodeJS application experiences a crash if incorrect parameters are provided to the API

Currently, I have built a CRUD API using TypeScript with Node.js, Express, and MongoDB. My goal is to ensure that the API functions correctly when the correct parameters are sent through a POST request. However, if incorrect parameters are passed, the Node ...

The isInvalid property fails to apply red highlighting to the input box in a react-bootstrap form

Working on creating forms using React and react-bootstrap. Currently, my form includes an email field structured like this - https://i.sstatic.net/dlbWn.png Here's the code snippet of how it looks: <Form noValidate autoComplete="off&quo ...

Ordering and displaying data with AngularJS

Trying to maintain a constant gap of 5 between pagination elements, regardless of the total length. For instance, with $scope.itemsPerPage = 5 and total object length of 20, we should have 4 pages in pagination. However, if $scope.itemsPerPage = 2 and tota ...

Unlocking the Secret: Retrieving Click Event Values from a jQuery Function

Is there a way to retrieve the onclick event value change in jQuery when clicking on a DIV? $("ul li").click(function(){ var newValue = $(this).val(); }); $(function(){ alert(newValue); }); ...

The NVD3 tooltip is being obscured by other divs

Attempting to make the NVD3 tooltip appear above all other divs has presented a challenge. With three charts lined up horizontally and tooltips that exceed the boundaries of their divs, adjusting the z-index creates a dilemma. Regardless of which side&apos ...

Save the click value for future use

My appointment form is divided into separate panels. At Step 1, if a user clicks on London (#Store1), I want to hide the Sunday and Monday options from the calendar in panel 5. Essentially, I need to save this click event so that when the user reaches th ...

Tips for managing cross-referencing visibility between two distinct div elements using AngularJS

Currently, I am working on an AngularJS project and facing a specific issue that I need help with. I have two div elements to deal with. The first div contains a list of images as anchors which are generated using the ngRepeat directive. The second div s ...

What is the best way to iterate over JSON data and organize the output based on the key value?

Let's say I want to filter through the JSON data below and only push the home_team_conference if it matches Southeastern. My goal is to organize the data by home_team_conference in order to display each array on different pages of my website. Currentl ...

What is the best way to merge different Vue JS instances (each linked to different html divs) into one cohesive unit using Vue

Essentially, I have a scenario where I've created two HTML divs named vueapp1 and vueapp2. Both of these divs serve the same purpose of displaying information and are linked to their individual Vue instances for extracting JSON data and presenting it. ...

The essence of responsiveness within personalized widgets

To create a vertical slider input, I had to find an alternative option since the built-in sliderInput function does not support it. After exploring this thread, I learned that there are two possible solutions: (I) rotating the sliderInput widget using CSS ...

Managing state in React using a nested object structure with React hooks for adding or updating entries

In my React application, I have a state object that represents a book structure consisting of books, chapters, sections, and items: const book = { id: "123", name: "book1", chapters: [ { id: "123", name: "chapter1", sections: [ ...

Issue with event listener arising once elements have been loaded into the dom

I have a project where I want to click on a category card to obtain its id and then redirect to the movies screen. I understand that using row.eventlistener() in index.js executes before the elements are rendered, causing the id not to be captured. How ca ...

Error in Node.js Express: Attempted to access property 'image' of null resulting in an unhandled error event

I've been trying to identify where the issue lies. Can someone lend a hand with this? When attempting to submit the post without an image, instead of receiving a flash message, the following error pops up: and here's the source code link: https: ...