The ng-bootstrap modal fails to appear when incorporating [formGroup]="FormName" or formControlName="elementName"

Utilizing ng-bootstrap to create a popup modal has been a challenge for me. When I import FormsModule and ReactiveFormsModule in src/app/modal-basic.module.ts, the code inside it looks like this:

import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 
import { BrowserModule } from '@angular/platform-browser';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { NgbdModalBasic } from './modal-basic';
@NgModule({
  imports: [BrowserModule, NgbModule, FormsModule, ReactiveFormsModule],
  declarations: [NgbdModalBasic],
  exports: [NgbdModalBasic],
  bootstrap: [NgbdModalBasic]
})
export class NgbdModalBasicModule {}

Furthermore, when I declare a FormGroup in src/app/modal-basic, the code inside it becomes:

import {Component} from '@angular/core';
import {FormGroup} from '@angular/forms';
import {NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'ngbd-modal-basic',
  templateUrl: './modal-basic.html'
})
export class NgbdModalBasic {
  closeResult = '';
  exampleFormName: FormGroup;
  constructor(private modalService: NgbModal) {}

  // More code here...
}

In src/app/modal-basic.html, when I add [formGroup]="exampleFormName" to the form tag or formControlName="elementName" to a control element, the code looks like this:


// HTML code block here...

After making these modifications, the popup modal does not behave as expected. It appears after the last element on the page instead of popping up. I am seeking assistance to identify the issue. Kindly try the code from ng-bootstrap without my modifications, then copy the code here and paste it in StackBlitz to diagnose the problem. Thank you in advance.

Answer №1

To properly handle the inputs, make sure to use FormControl within your FormGroup:

Check out this example on StackBlitz

import { Component } from "@angular/core";
import {FormGroup, FormControl} from "@angular/forms"
import { NgbModal, ModalDismissReasons } from "@ng-bootstrap/ng-bootstrap";

@Component({
  selector: "ngbd-modal-basic",
  templateUrl: "./modal-basic.html"
})
export class NgbdModalBasic {
  closeResult = "";
  exampleFormName = new FormGroup({
    name: new FormControl(),
    dateOfBirth: new FormControl()
  });
  constructor(private modalService: NgbModal) {}

  open(content) {
    this.modalService
      .open(content, { ariaLabelledBy: "modal-basic-title" })
      .result.then(
        result => {
          this.closeResult = `Closed with: ${result}`;
        },
        reason => {
          this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
        }
      );
  }

  private getDismissReason(reason: any): string {
    if (reason === ModalDismissReasons.ESC) {
      return "by pressing ESC";
    } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
      return "by clicking on a backdrop";
    } else {
      return `with: ${reason}`;
    }
  }
}

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

Utilizing the component as both a custom element and an Angular component

I have been experimenting with using an Angular component as a custom element, allowing me to dynamically add it to the DOM and have it automatically bootstraped. However, I also need this component to be included in another component's template. Cur ...

Having trouble with jQuery after adding more content?

I recently started delving into the world of javascript, incorporating it into my website. Just last week, I came across a script that utilizes jQuery to load extra content onto my page. Initially, everything seemed to be functioning smoothly until I reali ...

Obtain the current date using Moment JS in JavaScript

Here is a scenario with code : let currentTime = moment(); console.log(currentTime.format()); // 2019-11-25T20:23:50+02:00 console.log(currentTime.toDate()); // 2019-11-25T18:23:50.916Z After applying the timezone change on Heroku using the command ...

Efficiently showcase connected pages in real-time

I've come across an issue with my express app. Whenever a navigation link (such as Home, Home1, or Home2) is clicked, an error occurs. However, if I manually type in http://localhost:8001/home1, it displays home1.html without any issues. What I' ...

Vue.js compatibility issue with SelectBoxIt jq plugin causing malfunction

On a page with numerous dynamically generated select boxes, I am looking to incorporate the jQuery selectBoxIt plugin from . Using Vue js, where is the best placement for the following code snippet to connect the plugin with the select elements? $('. ...

Transforming a flow type React component into JSX - React protocol

I have been searching for a tooltip component that is accessible in React and stumbled upon React Tooltip. It is originally written in flow, but I am using jsx in my project. I am trying to convert the syntax to jsx, but I'm facing difficulties with t ...

Managing asynchronous data retrieval using rxjs

Within my service, I use an Observable to load data in the constructor. Later on, this data can be accessed using a getter, which should either return the data immediately if it's available or wait until the loading process is complete. Here is an exa ...

Highlighting Search Results in Kendo TreeView

I am currently working on a KendoTreeview project with spriteclass. My goal is to highlight both the root and child nodes with a specific search term. I have successfully implemented the search functionality, however, there is an issue that arises after th ...

Incorporating a JavaScript variable into an inline HTML onclick event

Having trouble passing a variable into an inline onclick function. I've tried researching and following suggestions from this link, but encountered errors (Uncaught SyntaxError: missing ) after argument list): pass string parameter in an onclick func ...

Tips for sending a div value that is not included in the model to the backend controller action

Question: I am looking to have a single div element in the user interface that can display a value added via JQuery and then be accessible in the backend once the form is submitted. View: @model ScheduleAptMV using (Html.BeginForm()) ...

The iPad scroll did not meet the condition for reaching the bottom

Looking to modify the footer when the bottom of the page is reached via scrolling, I implemented the following code: if($(window).scrollTop() + $(window).height() == $(document).height()) This condition successfully detects whether the scroll has reached ...

The Angular application's "wait" dialog fails to appear

I'm currently setting up a dialog that includes a mat-spinner while the page data is loading in an Angular v14 project. Instead of using a basic spinner, I opted for a dialog because I need to pass some additional information within it. However, I&apo ...

When faced with the error message "Typescript property does not exist on union type" it becomes difficult to assess the variable

This question is a continuation of the previous discussion on Typescript property does not exist on union type. One solution suggested was to utilize the in operator to evaluate objects within the union. Here's an example: type Obj1 = { message: stri ...

Formatting dates in a C# MVC application after parsing JSON

I am working on an MVC application that retrieves data from a SQL database and passes it to a view. One of the views contains a Kendo grid that displays the data, including a date column. The date data is stored in the SQL database as DateTime, while the m ...

Enhance your Three.js development with TypeScript autocomplete

In my project using Node.js, Typescript, and Three.js, I have set up the commonjs syntax for module imports in my tsconfig.json file like this: { "compilerOptions": { "module": "commonjs" } } I installed Three.js via NPM and created a typescript ...

Converting a variable with a cloned object from jQuery to vanilla JavaScript

const clonedBoardCode = $('#board_code').contents().clone(false); alert( clonedBoardCode.filter('div').eq(x).children().eq(y).text() );//need to fix this I am looking for a code similar to this $('#board_code_dup > div') ...

Uncovered requirement for the selectSignal in an isolated module

While trying to utilize selecctSignal in a standalone component, I encountered a runtime error: ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(Standalone[AllTablesHeadComponent])[signal -> signal -> signal -> signal]: N ...

Utilizing ajax for fetching a data table

I am new to using ajax and have successfully retrieved data from a table. However, I am now trying to pull in an entire data grid but not sure how to achieve this. In my index.php file, I have the following code: <html> <head><title>Aj ...

What is causing the Unhandled Rejection (TypeError) error after I move the object in my Redux application and receive the message "Cannot read property 'filter' of undefined"?

I've been working on a Redux application. I've made modifications to a couple of files, and here are the changes in the two files: index.js: const store = createStore( reducer, { propReducer: { day: 1, data: [], filte ...

utilize jquery ajax to input various data

I am attempting to include multiple data in a jQuery ajax call. However, my current implementation is not working as expected. The data fetched is taken from the following span: <span id="<?php echo $tutorial_id; ?>" modes="<?php echo $modese ...