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

Tips for troubleshooting the flowbite modal issue in vue js

Currently, I am utilizing Vue.js along with Tailwind CSS and Flowbite for component library support. However, I am encountering an issue with the modal component from Flowbite. Despite following the installation and configuration steps outlined in the docu ...

Displaying errors above the table. Executing ng-repeat in AngularJS

I've been struggling with a seemingly simple issue for hours now. I have a table displaying equipment rows using ng-repeat and input controls, and I want to display validation errors above the table. Here's what I tried: <div class="col-xs- ...

Tips for incorporating local storage into Angular applications

After successfully creating a table using Angular, I decided to incorporate a local storage feature. Despite my efforts, I'm struggling with implementing gsklee/ngStorage and gregory/angular-local-storage libraries into my existing code. Could someon ...

Creating a null array of a specific size can easily be accomplished in Typescript

When I use the splice method to add elements to an array at a specified index, I find myself creating a null array first in order to achieve this. If I use an empty array instead, the elements do not get pushed to the specific instance that I intended. Cur ...

In the realm of JavaScript and TypeScript, the task at hand is to locate '*' , '**' and '`' within a string and substitute them with <strong></strong> and <code></code>

As part of our string processing task, we are looking to apply formatting to text enclosed within '*' and '**' with <strong></strong>, and text surrounded by backticks with <code> </code>. I've implemented a ...

Seeking out a particular key within a JSON object and then finding a match based on the id within that key's array - how can it be

Recently, I've been exploring JavaScript and encountering challenges when trying to apply array methods on objects. For instance, I received a fetch response and my goal is to extract the 'entries' key and then utilize the native Array.find( ...

Angular 16 HttpClient post request with asynchronous action

Here I am working on integrating JWT in Angular with a .Net Core API. When I start my Angular server and launch the application, I encounter the following scenarios: Attempting with correct credentials initially fails, but retrying allows it to work. Tryi ...

Struggling to make $http post requests to PHP using Angular

I am experiencing difficulties in transferring data to my PHP file after decoding Json, resulting in an error. I need assistance in identifying where I have made a mistake. app.js $scope.formPost = function(){ $http.post('sendmail.php' ...

How to create horizontal spacing between divs using Bootstrap 3

I am struggling to create a small horizontal space between the "Away Team" and "Baseball Field" divs in my code. I have tried adjusting padding, margins, and even adding decimal column offsets without any success. The desired spacing effect can be seen in ...

Directive attribute causes unit test failure

Declare a directive as an Attribute: app.directive('myDirective', function() { return { restrict: 'A', replace: true, transclude: true, scope: { data: "=" }, template: ...

Is it possible to customize a VSCode extension to function exclusively with certain programming languages?

Lately, I added a new extension to my VSCode setup that has proven to be quite beneficial for my workflow. If you're interested, you can find this helpful extension at This Repository. It allows you to easily highlight the starting and ending syntax ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

Incorporating the id attribute into the FormControl element or its parent in Angular 7

I'm attempting to assign an id attribute to the first invalid form control upon form submission using Angular reactive forms. Here is my current component code: onSubmit() { if (this.form.invalid) { this.scrollToError(); } else { ...

The ng-repeat in the inner loop is excluding the initial element of my array and subsequently placing them in the final HTML tag

I am facing a challenge with converting a JSON array into HTML using angular's ng-repeat. The JSON structure I'm working with looks like: data:{ thing_one:[{ id:1, fields:[{ .... }] }, { id:2, fields:[{ .... ...

React, redux, and redux observable are all essential tools for developing web applications. They

I am currently working on determining the type of a promise's resolve function. Here is a snippet of the code, or you can find it on GitHub: https://github.com/Electra-project/Electra-Desktop/blob/master/src/app/header/epics.ts export function getSt ...

Cannot send response headers once they have already been sent to the client [NEXTJS]

Currently, I am engrossed in a personal project focused on creating a dashboard using NextJS. This project serves as an opportunity for me to delve into learning NextJS and the fundamental concepts of TypeScript. My primary challenge at the moment revolves ...

Uploading and cropping multiple images in AngularJS

Currently in search for quality Angularjs code that offers support for multiple image uploads along with cropping capabilities. After extensive searching, I have come across either solutions that excel at multiple image uploading or ones that specialize i ...

Angular- Table button placement

I have a requirement where I need to display a button in a table, but the button should only show when the "name" value is set to "False". If the "name" value is set to "True", then the button should not be displayed. This is my Json data: [ { ...

Validate object containing both static and dynamic keys

I'm attempting to create a Yup validation schema for an object with the following structure: interface myObject { prop0: Date prop1: { nestedProp1: string nestedProp2: number [key: string]: string | number } } This is what I have tr ...

The absence of the import no longer causes the build to fail

Recently, after an update to the yup dependency in my create react-app project, I noticed that it stopped launching errors for invalid imports. Previously, I would receive the error "module filename has no exported member X" when running react-scripts buil ...