Best practices for creating a versatile modal component

I have come across a few examples, but they all appear to be contradictory or intended for older versions of ng-bootstrap.

What is the correct method for creating a basic modal that can be stored in a shared directory and then used for multiple modals on a single page? I would like to pass a form component as the content of the modal.

Although I have viewed the example on the official website, it does not account for having multiple modals/modal triggers on one page. It assumes only a single modal without any specific targeting. I require the ability to pass an id for editing a data field within the modal and saving the changes to the database.

Answer №1

My experience was quite similar, where I tackled the issue by developing a basic Modal and embedding it in the HTML code

<div id="InformUser" class="modal fade active" role="dialog" data-backdrop="static">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">Status</h4>
                </div>
                <div class="modal-body">
                    <h5><i class="fa fa-info-circle fa-3x"></i><b>{{message}}</b></h5>
                    <br />
                    <br />
                    <button type="button" class="btn btn-success" data-dismiss="modal">OK</button>
                </div>
            </div>
        </div>
 </div>

I utilized this same modal for displaying various types of messages, which were assigned in the AngularJS Controller.

$scope.message = "My Message";

You may want to experiment with a similar approach. In your scenario, consider using ng-show or ng-hide to reveal different Form elements based on specific trigger IDs instead of solely relying on the Modal ID.

Answer №2

Learn how to create a versatile modal layout

To start, insert the modal layout code:

<!-- The Basic modal structure -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalLabel"></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" style="font-size:19px;">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">

            </div>
        </div>
    </div>
</div>

Next, utilize jQuery to activate the modal:

$(document).on('click', '.click-btn', function () {
    var dataURL = $(this).attr('data-href');
    var id = $(this).attr('id');
    $('.modal-title').html(id);
    $('.modal-body').load(dataURL, function () {
        $('#myModal').modal({ show: true });
    });
});

Note: dataURL should contain the modal content you wish to showcase.

Trust this approach proves beneficial to you

Answer №3

After spending countless hours grappling with the same issue, I finally found a solution that allows for multiple modals with unique bodies and functionalities while sharing common header and footer elements.

The key is to create a modal component with predefined header, footer, and basic button actions, along with a modal body where you can insert different content using ng-content. Here's an example:

<header class="modal-header">
  <h5 class="modal-title">
    {{ title }}
  </h5>
  <button type="button" class="btn-close" aria-label="Close window" (click)="dismiss()"></button>
</header>

<div class="modal-body">
  <ng-content></ng-content>
</div>

<footer class="modal-footer">
  <ng-template #readonly>
    <app-close-btn (clicked)="dismiss()"></app-close-btn>
  </ng-template>
  <ng-container *ngIf="!isReadonly; else readonly">
    <app-cancel-btn (clicked)="onDismiss ? onDismiss() : dismiss()"></app-cancel-btn>
    <app-save-btn [disabled]="isCloseDisabled" (clicked)="onClose ? onClose() : close()"></app-save-btn>
  </ng-container>
</footer>

export class ModalComponent {
  @Input() activeModal?: NgbActiveModal;
  ...
}

Then, create a component with the desired body content and use the above modal as its base.

export class YourModalBodyComponent extends ModalComponent {
constructor(readonly activeModal: NgbActiveModal) {
    super();
  }
}
<app-modal [activeModal]="activeModal" [title]="'Selecting study program'">
  This is your modal body
</app-modal>

Finally, open the modal using NgbModal.

The alternative approach involves creating a Modal class with shared logic, injecting NgbActiveModal, and utilizing ModalHeader and ModalFooter components in each individual modal. Unfortunately, most tutorials and demos I came across did not offer this level of template and logic reusability.

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

The functionality of ShowMaskOnFocus feature is not functioning properly for input masks in Angular

I am currently utilizing the input-mask library and trying to apply a mask for time format. I specifically need it to accept only integer numbers in HH:mm format, so here is what I have done: timeInputMask = createMask({ mask: '[99:99]', ...

Angular is able to successfully retrieve the current route when it is defined, but

Here's the code snippet I am working with: import { Router } from '@angular/router'; Following that, in my constructor: constructor(router: Router) { console.log(this.router.url); } Upon loading the page, it initially shows the URL a ...

Storing information from a signup form using Angular

Can you help with my registration form? <div class="form-group"> <label for="email" class="col-sm-3 control-label">Email Address</label> <div class="col-sm-9"> <input type="email" id="email" placeholder="Enter your ...

Need help with npm installation woes? In search of tips on ensuring version compatibility for Angular V16?

I've been facing numerous challenges with npm installation recently and could really use some guidance. Whenever I attempt to execute npm install, I consistently encounter version compatibility errors that disrupt my development process. It's bec ...

Dynamic property Key in TypeScript

Imagine receiving data from a search engine in the following format: const resultDe = { details_de: "Ein paar Informationen", foo_de:{bar:"barDe"}, code: "1C60" } const resultEn = { details_en: "Some information", fo ...

What is the correct way to refer to "this" within an Angular2 component template?

I'm working with an Angular2 component that looks like this: class A { filter(..) } Within the template for A, I have <.. list | pipe:filter ..> The issue arises when I call filter inside of the pipe - I don't have access to "this" w ...

Error encountered when trying to use the .find function in Typescript: "The expression is not callable."

Environment Details: typescript 4.5.5 Error Summary An issue occurred stating: "This expression is not callable. Each member of the union type '{ <S extends User>(predicate: (this: void, value: User, index: number, obj: User[]) => value ...

Angular 2: The Power of Services

Hello everyone, I am currently exploring Angular 2 and delving into the world of HTTP services. As I work on a service to create a form as well as an addFormation service, I encountered an issue where validating a formation in my form results in the addit ...

What is the best way to mark a specific photo as a favorite in an array of Photo objects?

I am working with a basic array of photo categories that follows this structure: [ { category: 1001, photos: [ { id: 100101, url: 'url.com/100101', favorite: false}, { id: 100102, url: 'url.com/100102', favorite: ...

Resolve the conflict with the upstream dependency in Angular

I understand that the solution to this issue can be found on SOF, but utilizing --legacy-peer-deps or --force is not an option for me on my production server. I am eager to comprehend the root cause of this error and find a proper resolution. Upon install ...

Utilize a service injected through dependency injection within a static constant defined within the component itself

Using Angular, I am trying to utilize a service that has been injected through dependency injection as a value for a static variable. Here is the scenario: Starting with the constructor where the Helper Service is injected: constructor(private _helper ...

Setting a maximum limit for selections in MUI Autocomplete

Code updated to display the complete script logic. I want to restrict the number of selections based on a value retrieved from the database, but in this example, I have set it to 3 manually. The error message I'm encountering is "Cannot read properti ...

The issue of the Angular 4 double click event not functioning properly on mobile devices

I have implemented a double click functionality in my code, which is working perfectly in desktop view. However, I am facing an issue when switching to mobile or tablet view as the double tap feature does not work. Below is a snippet of my code: HTML: & ...

The npm build command is triggering an error message that reads "Allocation failed due to ineffective mark-compacts near heap limit."

I'm currently working on a ReactJS/TypeScript project on Windows 10. I've been running into issues when trying to build my TypeScript scripts using the following command: "rimraf ../wwwroot/* && react-scripts-ts build && copyfi ...

Please exclude any files with the name npm-debug.log.XXXXXX in the .gitignore file

Is there a way to exclude this file from the repository using .gitignore? https://i.stack.imgur.com/mK84P.png I am currently working on Gitlab. I have attempted the following: https://i.stack.imgur.com/2kN21.png Appreciate any help in advance ...

Showing canvas lines while dragging (using only plain JavaScript, with React.JS if needed)

Is there a way to add lines with two clicks and have them visible while moving the mouse? The line should only be drawn when clicking the left mouse button. Any suggestions on how I can modify my code to achieve this functionality? Currently, the lines are ...

Leverage the component's recursive capabilities to build a tree structure from within

Is it feasible to use a component within itself? If so, where can I find more information on this? I am facing the following scenario: I have a list of main items, each main item has a subitem (which looks like the main item), and each subitem can have i ...

Ensuring the image is properly sized to fit the screen and enabling the default zoom functionality

I am looking to achieve a specific behavior with an image, where it fits the viewport while maintaining its aspect ratio and allowing for zooming similar to how Chrome or Firefox handle local images. Here are the details of my project: The image I have is ...

How to prevent Cut, Copy, and Paste actions in a textbox with Angular 2

I am currently utilizing Angular2 to prevent copying and pasting in a textbox. However, I am seeking guidance on how to create a custom directive that can easily be applied to all text fields. Here is the code snippet that successfully restricts the copy ...

Encountering issues when trying to combine Sequelize with TypeScript

As I attempted to transition my NodeJs application to TypeScript, I encountered issues with Sequelize. Upon attempting to implement the code from a website, an error occurred: This expression is not constructable. Type 'typeof import("/home/de ...