Discover the best way to cycle through bootsrap modal dialogs using angular

Within my component.ts file, there exists an array:

dummyData = ['1', '2', '3'];

The objective is to iterate through this array and generate 3 modals displaying values 1, 2, and 3 respectively.

Here's a snippet of the HTML code:

    <div *ngFor="let data of dummyData">
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Launch demo modal
  </button>
  <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          {{data}}
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>
</div>

The challenge lies in generating unique id and data-target values for each modal. Seeking guidance on how to accomplish this task efficiently. Any suggestions would be highly appreciated.

Answer №1

If you're following the bootstrap framework,

<div *ngFor="let data of dummyData">
  <!-- Button to trigger modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal{{data}}">
    Launch demo modal
  </button>
  <!-- Modal itself -->
  <div class="modal fade" id="exampleModal{{data}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          {{data}}
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>
</div>

Each button and modal will have a unique ID based on the content of each array element.

Answer №2

An issue that often arises with vanilla Bootstrap is the inability to effectively loop over elements using *ngFor and utilize string interpolation in IDs without triggering errors. Bootstrap may struggle to identify elements when this approach is taken.

To overcome this challenge, it is recommended to explore ngBootstrap. However, if customizing the appearance of components is a priority, complications can arise quickly. In such cases, opting for Material could be advantageous. Developed by the Angular team, Material is tailored specifically for Angular projects, providing a smoother and more efficient user experience.

Answer №3

After facing the same task, I managed to successfully complete it with the assistance of directives like [attr.data-target] and [attr.id].

Here is the revised HTML that provides a full solution:

<div *ngFor="let data of dummyData; let i = index">

<!-- Button trigger modal -->
<button type="button" [attr.id]="'triggerModalbutton-' + i" class="btn btn-primary" data-toggle="modal"
    [attr.data-target]="'#exampleModal-' + i">Launch demo modal</button>

<!-- Modal -->
<div class="modal fade" [attr.id]="'exampleModal-' + i" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
        </div>
        <div class="modal-body">
        {{data}}
        </div>
        <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
        </div>
    </div>
    </div>
</div>

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

Encountered an issue with ionViewDidLoad: The property 'firstChild' cannot be read as it is null

While working on an Ionic 2 App with Angular2 and Typescript, I encountered an issue when trying to pass a JSON to map for markers. Here is the link to the gist containing the code snippet I am facing an error that reads: view-controller.js:231 MapPage i ...

tips for incorporating datatable into ng bootstrap modal within an angular application

I am trying to create a data table within an ng-bootstrap modal in Angular using Bootstrap and the angular-data tables module. My goal is to display the data table specifically within a bootstrap modal. ...

Creating routes with dynamic components or importing dynamic components in Angular 2 is a versatile and powerful feature

Is there a way to dynamically create routes or import components based on data? For instance, suppose I have a JSON file with objects containing RouteNames, paths, and ComponentNames. How can I dynamically generate route definitions from this data? The ch ...

Angular 6 Error: Template Driven Form - Unable to access property 'required' in null entity

Struggling with validation issues while working on an angular 6 project with a template-driven form. Here is the HTML code snippet causing trouble: <div class="form-group"> <div class="form-group"> ...

Extend mat-table with 3 expanding columns and 1 clickable column

Is there a way to add different click events for specific columns of an Angular Material Table? Specifically, I would like the left column (Blue/LP) to trigger a click event that passes the LP value, while the right column triggers an expand action. Curren ...

What is the most efficient method to retrieve an API in Angular?

Recently, I dedicated some time to a personal Angular project. While working on it, I decided to experiment with making an API call to PokeAPI in order to retrieve the .svg image of a Pokemon along with its name. After successfully implementing this featur ...

I'm experiencing unexpected behavior with the use of Mat-Spinner combined with async in Angular 12, particularly when using the rxjs function

I am relatively new to rxjs and it's possible that I'm using the wrong function altogether. Currently, I'm working on a .NET Core 3.1 backend and implementing a two-second delay for testing purposes. I have a service call that I need to mock ...

Exploring ways to fetch an HTTP response using a TypeScript POST request

I have been looking at various questions, but unfortunately, none of them have provided the help I need. The typescript method I am currently working with is as follows: transferAmount(transfer: Transfer): Observable<number> { return this.http .po ...

Issue: Unable to find Store provider while using @ngrx/store in Angular 4.0

Issue: Error: No provider for Store! I am trying to initialize the store module in main.ts: platformBrowserDynamic().bootstrapModule(AppModule,[ provideStore({ characters, vehicles }) ]); Then I am injecting it into vehicle.component.ts: c ...

Angular - Enhance User Experience with Persistent Autocomplete Suggestions Displayed

Is there a way to keep the autocomplete panel constantly enabled without needing to specifically focus on the input field? I attempted to set autofocus on the input, but found it to be clunky and the panel could still disappear if I hit escape. I also ...

What is the best method to adjust the width of the PrimeNG ConfirmDialog widget from a logic perspective

Currently utilizing "primeng": "^11.2.0" and implementing the ConfirmDialog code below this.confirm.confirm({ header: 'Announcement', message: this.userCompany.announcement.promptMsg, acceptLabel: this.userCompany.announcement ...

Pass attribute names dynamically to a component in Angular 2 using a variable

Is there a way to pass data into a component while also storing the attribute name in a variable? For example: <app-note-form-sticky [foreign_key_column]="foreign_key_value"></app-note-form-sticky> In this case, "foreign_key_column" is the va ...

Experiencing an issue with my Angular 6.1.0 setup, using angular-cli 7 and primeng 7 - specifically encountering the error message "Initializers are not allowed in ambient context."

Issue encountered in the primeng package: While examining node_modules/primeng/components/picklist/picklist.d.ts, errors were found at line numbers 65 and 66. I have investigated the primeng package further. primeng/components/picklist/picklist.d.ts l ...

checkbox causing the button to appear empty

Due to the inability of a ngIf and ngFor to coexist, I added an ng-container to facilitate the loop. However, after making this change, nothing seems to be working as expected without any clear reason. Below is the code snippet that is causing trouble: Vi ...

Utilizing MSAL's loginRedirect within an Ngrx Effect: A step-by-step guide

Is there a way to utilize Msal angular's loginRedirect(): void function instead of loginPopup(): Promise in an Ngrx Effect? I've been able to successfully implement the loginPopup() method, but since loginRedirect() has a void return type, it di ...

Step-by-step guide on crafting a harmonious row of a label and a responsive button group

One of my projects involves a form that contains a list of elements. I want this form to be responsive and suitable for all screen sizes. When I initially run the project on a larger screen, everything looks good. However, when I resize the screen to a sma ...

Encoding URLs in Angular 2 for HTTP POST requests

I am attempting to utilize a service through post with Angular2. Below is my code snippet: var m_dataRequest = this.buildLoginUserPasswordRequest(password, key); let headers = new Headers({ 'Accept': '*/*', &apos ...

Unable to compile an Ionic 5 (angular) application with Node.js versions 12.22.12 or 12.22.6

I'm facing a challenge with an old app that requires me to run it using nvm for compatibility with older versions of node.js and ionic. Despite the outdated dependencies, I simply need to get it running in a development environment. Upon attempting t ...

Contrasting input: [] with the @Input() directive

Recently, I've begun exploring the world of child and parent component communication in Angular 4. In my research, I stumbled upon older videos that utilize the input: [] syntax instead of the now more prevalent @Input() syntax. Is there any distincti ...

Is there a way to determine the position of the highlighted text within a textarea?

Is there a simple way to calculate the position of the selected text within a textarea using vanilla JavaScript or Angular (possibly with a directive)? This is important in order to display a div with a popup above the selected text. Coordinates are need ...