Display Bootstrap Modal using Typescript in Angular

Looking for some creative ideas here... My Angular site allows users to register for events by filling out a form. They can also register themselves and other people at the same time. https://i.sstatic.net/a44I7.png

The current issue ~ when a user clicks "Add another ticket," it goes through a method that first validates all fields and checks if the checkbox is ticked. If any fields are invalid, an alert message appears indicating which fields need correction. The method then verifies if there are enough tickets available to add more attendees (this is what I'm currently working on - checking ticket availability). If there are sufficient tickets, the person is added to an 'attendees' array, and the form is reset to add more people.

If there aren't enough tickets to add more attendees, the 'Add another ticket' button is hidden, and a modal window pops up informing the user that no more tickets are available. The only option left is to click 'pay now' and complete the registration process for the lined-up attendees/tickets.

Since the 'Add another ticket' button cannot display the modal directly, I'm trying to implement this functionality in TypeScript. Currently, I have a test code displaying an alert message, but alerts are not very appealing visually.

Note that "Add another ticket" (along with attendee fields) acts as a child component, while the rest of the screen serves as the parent component. The parent triggers a method when the child's button is clicked:

public addAttendee(attendee: Attendee, waitlisted: boolean): void {
        // We ensure all fields are valid before adding an attendee. Display error message & quit otherwise.
        console.log("Add attendee button clicked");
        this.attendeeComponent.AddAttendeeTermOfSale = true;
        if (!this.attendeeComponent.areTheseFieldsValid(true)) {
            this.areFormFieldsValid = false;
            this.errorMessages = this.invalidFieldsAttendee();
            return;
        } else {
            this.areFormFieldsValid = true;
            this.attendeeComponent.AddAttendeeTermOfSale = false;
        }

        if (this.eventPassCapacityReached()) {
            this.cantAddAdditionalAttendees(); 
            return;
        }
        
        if (this.isAttendeeCountExceedingEventCapacity()) {
            this.showEventCapacityExceedingErrorMessage();
            return;
        }...
    }

The "EventPassCapacityReached" function validates ticket availability:

public eventPassCapacityReached() {
        let attendeesBeingRegistered = this.attendees.length;
        attendeesBeingRegistered += 1;
        this.sumPass = this.sumPass - attendeesBeingRegistered;

        if (this.sumPass <= 0)
            return true;
        else
            return false;
    }

Trying to replace the alert window...

public cantAddAdditionalAttendees() {
        this.attendeeComponent.isPassesSoldOut = true;
        alert("Oops... this was the last ticket for the event");
        var AddAttendeeButton = document.getElementById("AddAnotherAttendee");
        AddAttendeeButton.style.display = "none";
    }

Here's the modal in the view:

<div class="modal fade" tabindex="-1" id="noPassesModal" role="dialog" aria-labelledby="noPassesModalLabel" aria-hidden="true" data-target="noPassesModal">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">No additional tickets available</h4>
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                        <div class="modal-body">
                            <p>Unfortunately we don't have any additional tickets available for this event, and you wont be able to register additional people</p>
                            <p>If you have additional people who would like to come, we would suggest you contact our Events team via <a href="mailto:someemail@example.com">email</a> or by phone on 1800 161 236</p>
                        </div>
                        <div class="modal-footer">
                            <div class="row">
                                <div class="col align-self-end">
                                    <button role="button" class="btn btn-secondary btn-block">OK</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

Considering how to trigger this modal using TypeScript within "cantAddAdditionalAttendees":

Answer №1

A simple method for displaying the modal is to control it with a boolean variable in the typescript file.

Just set it to 'true' when you need to show the modal (in your cantAddAdditionalAttendees function). In your html, use *ngIf on the modal div.

This way, you can easily toggle the visibility of your modal by manipulating the boolean variable.

As modals become more complex and involve more functionality, it may be beneficial to move them into a separate component.

Another approach could be to utilize CDKComponentPortal to dynamically generate the Modal components.

However, using the boolean variable as described should suffice for your current scenario.

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

How can I verify the validity of a regular expression in Typescript without encountering a syntax error?

I am facing an issue with my code where I load a set of regular expressions from an external source. My goal is to determine if a given string is a valid regex without causing the application to crash due to a syntax error. Despite trying to use try/catch ...

Arranging an array based on relationships between children and parents

I have an array of objects like this: const data = [{id: 3, name: ''}, {id: 4, name: ''}, {id: 5, name: '', parent: 3}, {id: 6, name: '', parent: 5}, {id: 7, name: '', parent: 4}, {id: 8, name: '&ap ...

Send a variety of jQuery element selectors to a function

myFunc() is connected to the document scroll event, resulting in frequent calls. To optimize performance, I intend to store HTML selections in variables and then pass them to the function. However, upon running the code snippet below, an error appears in t ...

When a 404 error is thrown in the route handlers of a Next.js app, it fails to display the corresponding 404 page

I am encountering an issue with my route handler in Next.js: export async function GET(_: Request, { params: { statusId } }: Params) { const tweetResponse = await queryClient< Tweet & Pick<User, "name" | "userImage" | &q ...

The hover state of a div will not be lost if its parent element is not being hovered over

When hovering over the second, third, or fourth item, hidden text will appear on the left side. If you hover your cursor over the hidden text, it will disappear again. I want to be able to hover over the second item, move my cursor to "hide", and click o ...

Tips for adjusting a Bootstrap table to the size of the page it's on

app.component.html <html> <nav class="navbar navbar-expand-md"> <div class="container"> </div> <div class="mx-auto order-0"> <a class="navbar-brand mx-auto" href="#">GURUKULAM PRE-SCHOO ...

Add a new child component template with each click using the onclick event in Angular

Is there a way to dynamically add a child component with each button click event? Here is the HTML code for the button: <button type="button" class="btn btn-success btn-sm btn-add-phone" (click)="addfield()"><span class="fa fa-plus"></span ...

Utilizing TypeScript to spread properties onto a component and destructure them from within components

I'm trying to optimize my use of props spreading and destructuring when working with components. Currently, I spread my props in this manner: <RepositoryItem {...node} /> Then, within the component, I destructure the props like so: interface ...

The mysterious nature of view binding in Ember.js

Here's a unique challenge I'm facing. I've developed a sidebar component called SortableStopView that extends CollectionView. This sidebar contains a scrollable and sortable list of 'stops' which users can click on to navigate to t ...

Set up Nginx to host Angular static files and act as a reverse proxy for express

Recently, I've started using Nginx for serving static Angular files and proxying to a backend Express server. Both the frontend (with Nginx) and backend are dockerized. My frontend consists of a button that makes a request to fetch data from Express. ...

Can a virtual host proxy utilize an external IP address?

Currently, I have three node apps running on the same server but with different localhost ports. My goal is to create a router that acts as a proxy for each app and then place this proxy in a virtual host. While I am currently testing this setup on my loca ...

Error: Trying to access the 'title' property of an undefined variable in Vue.js

Creating a replica of hackernews by utilizing the axios API. The NewItem.vue component is not receiving any data, resulting in an error — TypeError: Cannot read property 'title' of undefined. Can you identify what's causing this issue in t ...

Implementing setInterval in ReactJS to create a countdown timer

I have been working on developing a timer application using React. The functionality involves initiating a setInterval timer when a user clicks a specific button. const [timer, setTimer] = useState(1500) // 25 minutes const [start, setStart] = useState( ...

How come the variable `T` has been assigned two distinct types?

Consider the following code snippet: function test<T extends unknown[]>(source: [...T], b: T) { return b; } const arg = [1, 'hello', { a: 1 }] const res = test(arg, []) const res1 = test([1, 'hello', { a: 1 }], []) The variabl ...

retrieve information from various components identified by the common class name by employing ajax requests

I have a component labeled with the class tclick indicating a sample class <label class="btn btn-default tclick" data-tloc="value1" data-tkey="key1" > <label class="btn btn-default tclick" data-tloc="value2" data-tkey="key2" > <label class= ...

Ways to conceal #div element from displaying in the href attribute within the anchor tag

My anchor tag has an href attribute that looks like this: <a onclick='loadReview(\"" + strexternalURL + "\");' href='#productName1'. When clicking on it, the URL appears as http://localhost:54986/Dealerlist.aspx#productName ...

Ways to retrieve the output parameter in the node mssql

` request.input('xyz',sql.Int,1); request.input('abc',sql.Numeric,2); request.output('pqr',sql.Int); request.output('def',sql.Char); request.execute('[StoredProcedure]',function(err,recor ...

What is the best way to implement a forEach loop within a JavaScript file?

$(document).ready(function() { $("form").on("click", ".addRow", function(){ var newRow = '<div class="row add tr">'+ '<div class="col" ...

Tips for sending get parameter data to a component in React

Currently, I am utilizing react (next.js) to develop a basic application. The specific issue I am facing involves creating a form in both add and edit modes. Depending on whether the get parameter contains 'edit', the form makes certain API calls ...

Rendering React component within a production build of Angular 7

I've been in the process of gradually moving an Angular app to React. After exploring options like single-spa and nx, I found that they weren't suitable due to the messy script-injected nature of the existing app. So, I decided to go for a semi-m ...