Creating a NgFor loop in Angular 8 to display a dropdown menu styled using Material

I'm currently facing an issue with incorporating a Materialize dropdown within a dynamically generated table using *ngFor. The dropdown does not display when placed inside the table, however, it works perfectly fine when placed outside.

<p>Users enabled in this node: {{usersEnabled}}</p>
<p>Users in this node: {{users.length}}</p>
<table>
    <thead>

        <th>
            Email
        </th>
        <th>
            Enabled
        </th>
        <th>
            Actions
        </th>
    </thead>
    <tbody>
        <tr *ngFor="let user of users">
            <td>
                {{user.username}}
            </td>
            <td class="isLink cursorIcon" (click)="enableDisableUser(user.apiKey)">
                {{user.enabled}}
            </td>
            <td>

                <!-- Dropdown Structure -->
                <!-- <button class="btn" (click)="resetPassword(user)">Reset password</button> -->
                <a class='dropdown-trigger btn' data-target='dropdown{{user.apiKey}}'>Drop Me!</a>
                <ul id='dropdown{{user.apiKey}}' class='dropdown-content'>
                    <li><a href="#!">one</a></li>
                    <li><a href="#!">two</a></li>
                    <li class="divider" tabindex="-1"></li>
                    <li><a href="#!">three</a></li>
                    <li><a href="#!"><i class="material-icons">view_module</i>four</a></li>
                    <li><a href="#!"><i class="material-icons">cloud</i>five</a></li>
                </ul>
            </td>
        </tr>
    </tbody>
</table>

Typescript crucial methods

ngOnInit() {
    this.getUsers();
  }

  private getUsers(): void {
    this.userService.getUsersByNodeApiKey(this.nodeKey).subscribe(
      res => {
        this.usersEnabled = res.filter((user: User) => user.enabled).length;
        this.users = res.sort((a, b) => a.enabled < b.enabled ? 1 : -1);
        M.AutoInit();
        var elems = document.querySelectorAll('.dropdown-trigger');
        var instances = M.Dropdown.init(elems, {autoTrigger: true});
      },
      err => console.error(err)
    );
  }

I am utilizing Angular 8 along with Materialize CSS 1.0

Answer №1

To achieve this, you must include [innerHTML] in order to incorporate dynamically generated html within your table as shown below:

[innerHTML]="user.dropdown"

In this case, user.dropdown could be an empty string declared in your .ts file or a specific value intended for use in the drop-down.

You may also consider using user.apiKey in your scenario.

Answer №2

When the user's data is available, try displaying the table/row in the view by including the following code snippet:

<ng-container *ngIf="users.length">
  <tr *ngFor="let user of users">
  .
  .
  .
  </tr>
</ng-container>

I hope this solution works for you!

Answer №3

Hello @Marc Serret i Garcia... I have discovered a solution that may work for you. Please give it a try:

<tbody>
    <tr *ngFor="let user of users">
        <td>
            {{user.username}}
        </td>
        <td class="isLink cursorIcon" (click)="enableDisableUser(user.apiKey)">
            {{user.enabled}}
        </td>
        <td>

            <!-- Dropdown Structure -->
            <!-- <button class="btn" (click)="resetPassword(user)">Reset password</button> -->
            <a class='dropdown-trigger btn' [attr.data-target]='user.apiKey'>Drop Me!</a>
            <ul [id]='user.apiKey' class='dropdown-content'>
                <li><a href="#!">one</a></li>
                <li><a href="#!">two</a></li>
                <li class="divider" tabindex="-1"></li>
                <li><a href="#!">three</a></li>
                <li><a href="#!"><i class="material-icons">view_module</i>four</a></li>
                <li><a href="#!"><i class="material-icons">cloud</i>five</a></li>
            </ul>
        </td>
    </tr>
</tbody>

Take note of the changes I made -

<a class='dropdown-trigger btn' [attr.data-target]='user.apiKey'>Drop Me!</a>

And also remember to adjust the id of the dropdown accordingly -

<ul [id]='user.apiKey' class='dropdown-content'>
. This worked for me, hopefully it helps you too.

Please refer to my stackblitz example for more details: https://stackblitz.com/edit/multipledropdown

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

Issue with Modal Box: Datepicker not Displaying Correctly

I have implemented a modal box in my webpage. When I click on a text field where a datepicker is added, it does not display anything. However, when inspecting the element using Chrome's developer tools, I can see that the 'hasDatepicker' cla ...

Utilize/Absolve/Add a Prefix to angular material scss styles

Issue I am facing a challenge with integrating angular material SCSS into my application. I want to ensure that these styles are isolated and scoped specifically for my application, as it will be embedded within a larger monolith. The goal is to prevent a ...

Are the missing attributes the type of properties that are absent?

I have a pair of interfaces: meal-component.ts: export interface MealComponent { componentId: string; componentQuantity: number; } meal.ts: import { MealComponent } from 'src/app/interfaces/meal-component'; export interface Meal { ...

How can I use the store command to retrieve the href value of a link using a css selector in Selenium?

Is there a way to store a URL from a link using CSS instead of xpath? store //tr[td[contains(.,'6 Day')]][1]/td[8]/a@href my_var open $my_var If so, how can I achieve this goal with css? I managed to use the following locator: store css= ...

How can I modify the appearance of the bootstrap scrollbar with scrollspy?

I'm struggling to modify the color of the scrollbar in Bootstrap scrollspy despite having a functional scrollbar. Here is an example of my code: HTML: <body> <div class="container, scrollbar" id="myScrollspy"> <div class=" ...

Creating dynamic grids in React.js by utilizing HTML

Currently, I am tackling one of the projects on FCC which is the Game of Life. Prior to diving in, my focus is on figuring out how to render a grid on the page. I aim to modify the table dimensions while ensuring it fits neatly within its container. The ...

reposition content according to screen size

In my web development project, I am utilizing both bootstrap and angular to create a component that includes a menu feature. My goal is to have the menu displayed in the navbar when the screen size is large, but switch it to a dropdown menu on smaller scr ...

The placement of the content in the Grid system seems to be off-kilter, not aligning properly with Bootstrap standards

I am facing an issue with the logo and navbar layout in my design. The design has 3 columns for the logo and 6 columns for the navbar, as shown in this image: https://i.stack.imgur.com/RpmJm.jpg However, when I run the code, they do not appear in the cor ...

"Converting the Request Body into Encoded

One challenge I am facing is the need to encode the body of all outgoing requests in my Angular application, including standard json. While using HttpClient to make requests, it appears that I do not have direct access to the serialization layer within Ang ...

How to set a default option in a dropdown menu using Angular 4

Many questions have been raised about this particular issue, with varying answers that do not fully address the question at hand. So here we go again: In my case, setting the default value of a dropdown select by its value is not working. Why is that so? ...

How to insert additional spacing within an input tag class in dynamic HTML using jQuery

When creating an html table dynamically from json data, I encountered an issue with adding space inside my input button control. It seems that after separating two classes with a space, the code is not functioning properly in this snippet environment. Howe ...

"Adding an Image to Another Image in HTML or JavaScript: A Step-by-Step

Hello there! I'm currently working on creating a status bar where I can add an image after another image. Let me explain my idea clearly. So, I have two images in GIF format: one is white and 10x10px, and the other one is black and also 10x10px. On ...

I am experiencing some unwanted movement of divs when I hide one element and show another. Is there a way to prevent this from happening

My webpage features a dynamic div that transforms into another div upon clicking a button. Although both divs share similar properties, clicking the button causes some elements to shift unexpectedly. Strangely enough, when the height of the replacing div i ...

Maintain division contents while navigating

I need a solution to keep my div (NewCall) open even when the user navigates between pages in my Single Page Application. The NewCall div is located in my layout page and is triggered by user click. However, whenever I navigate to another page, the div cl ...

HTML5 Video Frozen in Place on Screen's Edge

I am encountering a problem specifically on Webkit, particularly in web view on iOS. When I tested it on desktop Chrome, the issue did not appear. Here is the Portrait image and Here is the Landscape image The video seems to be fixed in one position rega ...

Tips for resizing a larger image to display only a specific portion in CSS (and incorporating JS if needed)

I need to resize an image that measures 1024x1024 and is segmented into 4 quadrants: My goal is to reduce the size of this image so that quadrant 2 is 256x256 while masking out or hiding the remaining 3 quadrants, displaying only the desired section on th ...

Utilizing SASS, JavaScript, and HTML for seamless development with Browser Sync for live syncing and

I've been on a quest to find a solution that covers the following requirements: Convert SASS to CSS Post-process CSS Minify CSS Move it to a different location Bundle all Javascript into one file Create compatibility for older browsers Tre ...

Automatically update the cart count in the header component in Angular 6 when a product is added to the cart, without the need to

I am working on an E-Commerce application using Angular 6. I am facing an issue with updating the shopping cart count in the header component whenever a product is added or removed from the cart. The cart count only updates when I refresh the page. I have ...

My component reference seems to have gone missing in angular2

Trying to load my Angular 2 app, I encountered this error: https://i.stack.imgur.com/FmgZE.png Despite having all the necessary files in place. https://i.stack.imgur.com/kj9cP.png Any suggestions on how to resolve this issue? Here is a snippet from ap ...

Enhanced Compatibility of HTML5/CSS3 Modal Box with Internet Explorer

I'm experimenting with HTML5/CSS3 for the first time and have implemented a cool little link to display a dialog (modal) on one of my web pages. While this works perfectly in Chrome/Firefox, it unfortunately doesn't function properly in Internet ...