Creating a modal dialog using a function in a TypeScript file

Hey there, fellow developers!

I have a question that might seem simple.

So, in my HTML code I've got a Modal Dialog that pops up using ng2 Bootstrap. It's working fine, but... I want to replace this line of code

"<button class="btn btn-primary" (click)="showModal()">Login</button>"

(showModal())

and turn it into a function in my TypeScript file like this:

showModal(modal: ModalDirective) {

  }

Any tips on how I can achieve this? I've been struggling for over an hour now.

Here's the full HTML Code:

<button class="btn btn-primary" (click)="showModal()">Login</button>

<!-- Modal -->
<div bsModal #lgModal="bs-modal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" (click)="lgModal.hide()" aria-label="Close">
          <span aria-hidden="true"> &times;</span>
        </button>
        <h4 class="modal-title">Login</h4>
      </div>

      <div class="modal-body">
        <form id="myForm" role="form" [ngFormModel]="CreateGroup">
          <div class="form-group">
            <div class="input-group">
              <input type="text" [(ngModel)]='demoInfo.name' class="form-control" ngControl='name' placeholder="Username">
              <label for="uLogin" class="input-group-addon glyphicon glyphicon-user"></label>
            </div>
          </div>

          <div class="form-group">
            <div class="input-group">
              <input type="password" [(ngModel)]='demoInfo.password' class="form-control" ngControl='password' placeholder="Password">
              <label for="uPassword" class="input-group-addon glyphicon glyphicon-lock"></label>
            </div>
          </div>
        </form>

        <div class="modal-footer">
          <button type="button" [disabled]='!CreateGroup.valid' (click)="addNewGroup(demoInfo)" class="btn btn-primary">Login</button>
        </div>
      </div>

    </div>
  </div>

And here's my full TypeScript code:

import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { CORE_DIRECTIVES, FORM_DIRECTIVES, Control, ControlGroup, FormBuilder } from '@angular/common';
import { ModalDirective, BS_VIEW_PROVIDERS} from 'ng2-bootstrap/ng2-bootstrap';


class DemoInfo {
  name: string;
  password: string;
}

@Component({
  template: require('./template.component.html'),
  directives: [FORM_DIRECTIVES, CORE_DIRECTIVES, ModalDirective],
  viewProviders: [BS_VIEW_PROVIDERS]
})

export class ModalComponent {
  CreateGroup: ControlGroup;
  demoInfo: DemoInfo;
  modal: ModalDirective;
  constructor(fb: FormBuilder) {
    this.demoInfo = new DemoInfo();


    this.CreateGroup = fb.group({
      'name': new Control(this.demoInfo.name),
      'password': new Control(this.demoInfo.password)
    })
  }
  addNewGroup(demoInfo: DemoInfo) {
    console.log(demoInfo, 'whole object');
    this.demoInfo = new DemoInfo();
  }

  showModal(modal: ModalDirective) {

  }

  hideModal(modal: ModalDirective) {

  }

}

Answer №1

Here is the approach I took:

  1. To start, I included

    @ViewChild('lgModal') modal: any;
    in My ModalComponent

  2. Next, I created a new function named showModal()

  3. Lastly, I called this function by using this.modal.dosomething();

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

It is not necessary to specify a generic type on a Typescript class

When working with Typescript and default compiler options, there are strict rules in place regarding null values and uninitialized class attributes in constructors. However, with generics, it is possible to define a generic type for a class and create a ne ...

Using Angular 2, you can pass an object as a parameter to a function

Is there a way to pass an object as a parameter in the DOM on this forum? Within my HTML code, I have the following: <div class="list-items"> <ul> <li *ngFor="let i of item"> <span (click)="onAdd({{newUser.us ...

Tips for verifying the contents of a textbox with the help of a Bootstrap

I am still learning javascript and I want to make a banner appear if the textbox is empty, but it's not working. How can I use bootstrap banners to create an alert? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&g ...

What is the purpose of the tabindex in the MUI Modal component?

Struggling with integrating a modal into my project - it's refusing to close and taking up the entire screen height. On inspection, I found this troublesome code: [tabindex]: outline: none; height: 100% How can I remove height: 100% from the ...

Seeking clarification on how to load an angular directive

I am puzzled by the fact that in the given jsFiddle, 'here is a log' gets printed three times. http://jsfiddle.net/wg385a1h/5/ $scope.getLog = function () { console.log('here is a log'); } Could anyone shed some light on why thi ...

Include module A in module B, even though module A has already included module B's Angular

Currently, I am facing an issue with circular dependencies between two modules - User and Product. The User Module has already imported the Product Module to utilize the ProductListComponent. Now, I need to import/use the UserListComponent from the User Mo ...

What are the steps for integrating bootstrap into an Angular project?

I recently added Bootstrap to my Angular project using the npm install bootstrap command and referencing the necessary CSS file in the styles property of the angular.json file. However, when I run my application, I notice that Bootstrap is not being applie ...

The unpredictable behavior of the `this` keyword while troubleshooting a TypeScript program in VS code

Upon further investigation, it seems that the issue I encountered was related to using Chrome for debugging my full application. This led me to question whether the problem stemmed from TypeScript or VS Code. Before submitting my findings, I decided to sw ...

Struggling to destructure props when using getStaticProps in NextJS?

I have been working on an app using Next JS and typescript. My goal is to fetch data from an api using getStaticProps, and then destructure the returned props. Unfortunately, I am facing some issues with de-structuring the props. Below is my getStaticProp ...

Unable to provide any input while utilizing npm prompts

After installing npm prompts, I encountered a strange issue. When trying to run the example code for npm prompts, I found that I couldn't enter any input at all. The underscore in the input field would blink for a few seconds, then the cursor would ju ...

Angular two-way selection of dependent dropdowns

I am working on creating a dependent select/dropdown feature. Here is a sample JSON data that I have: [ { "id": 15695, "username": "user1", "address": { "id": 16794, "location": "O Treviño de San Pedro" }, "jobs": [ ...

Error: unable to locate module that was imported from

Every time I try to run the project using this command, an error pops up: > npm run build npm info using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7a9b7aa87fee9f1e9f0">[email protected]</a> npm info using ...

The next column featuring a dropdown menu

My goal is to make this sketch operational. The red elements in the sketch need to be programmed. Currently, I am using angularJS and bootstrap with the following code: <div class="col-md-6"> <div class="form-group"> <label&g ...

What is the best way to enable external events for Fullcalendar in an Angular environment?

Struggling to integrate external events with Fullcalendar and Angular. Admittedly, I am new to Angular and there are aspects that still elude me. Fullcalendar provides a guide on setting up with Angular, available here. Initially, I managed to set up the ...

Is combining AngularJS and Durandal the way to go?

Can AngularJS be integrated into a Durandal project seamlessly? Our team is currently utilizing Durandal, but we are considering transitioning to AngularJS while ensuring that the site continues to function properly. Is this a feasible undertaking and woul ...

Discover the best way to dynamically access the current user who is logged in using angular-meteor with ionic!

My goal is to have $scope.me reflect the currently logged-in user in real-time. However, I am facing an issue where even after a user logs out and logs back in as a different user, the variable $state.me still holds the old value until the page is refreshe ...

Injecting dynamic templates in Angular 7

Let me simplify my issue: I am currently using NgxDatatable to display a CRUD table. I have a base component named CrudComponent, which manages all CRUD operations. This component was designed to be extended for all basic entities. The challenge I am en ...

What strategies can I use to preserve type narrowing when utilizing the Array.find method?

Within the code snippet below, I am encountering a typescript compilation error specifically in the Array.find method. Despite checking that `context.params.id` is not `undefined`, my type seems to lose its narrowing. I'm puzzled as to why this type ...

An issue with modalInstance injection in AngularJS causing an error

MyAdmin.controller('AdminMasterController', ['$rootScope', '$q', '$scope', '$http', 'ApiCall', 'DTOptionsBuilder', 'DTColumnDefBuilder', '$window', 'myStorageSer ...

It is possible that the object may be null, as indicated by TS2531 error

I was interested in using QrReader to scan a file based on [https://github.com/Musawirkhann/react_qrcode_generation_scanner This code is written in react, but I wanted to use it with tsx. However, when attempting to implement it, I encountered an error: ...