Utilize ngFor to showcase additional items preceding the initial element

Is there a way to display an array using ngFor, but have a card displayed before the first element that opens a modal when clicked?

https://i.sstatic.net/6QG0D.png

Here is the code snippet for reference:

<div fxFlex="25" *ngFor="let product of products; let i = index">
    <div *ngIf="i == 0">                           
        <mat-card (click)="addProduct()" class="mat-card-add-button">
            <div fxLayout="row" fxLayoutAlign="center center" fxFlex="100%">
                <span style="font-size:32px;text-align:center">+<br />Add product</span>
            </div>
        </mat-card>
    </div>

    <div fxLayoutAlign="center stretch">
        <mat-card class="product">
            <img mat-card-image src="{{product.picture.url}}" alt="photo">
            <mat-card-title>{{product.name}}</mat-card-title>
            <mat-card-content>
                <p>
                    {{product.description}}
                </p>
            </mat-card-content>
            <mat-card-actions align="end">
            </mat-card-actions>
        </mat-card>
    </div>
</div>

Currently, the code displays the first element (the card) and the second element like this:

https://i.sstatic.net/FmHia.png

Any suggestions on how to fix this issue? Thank you!

EDIT :

ngFor loop products :

first loop => my card "add product"
second loop => product A

EDIT 2 : For assistance with alignment of mat-cards content, refer to this post: Align mat-cards content (image, text and buttons)

Answer №1

To achieve the layout you described, I made some adjustments to your code. You can view a working example on this stackblitz. I utilized @angular/flex-layout as much as possible while minimizing the use of CSS.

UPDATE: I have made additional changes to the stackblitz based on a comment / follow-up question. The modifications are detailed in my answer to the follow-up question.

Explanation

To start, you do not need to place your button within the loop of the products. You can restructure your code like this:

<div class="container">

    <mat-card>
      <!-- your button content -->
    </mat-card>
        
    <mat-card>
      <!-- the loop -->
    </mat-card>

</div>

Next, apply the necessary flex-layout attributes.

Since the button is now outside the loop, you should define the layout attributes on the container:

<div class="container" fxLayout="row wrap" fxLayoutAlign="center center" fxLayoutGap="25px"> ... </div>

To ensure the styling consistency between the mat-card containing the button and the mat-cards containing the products, set the width using the fxFlex attribute, for example:

<mat-card fxFlex="180px" ... class="product"> <!-- button content --> </mat-card>
<mat-card fxFlex="180px" ... class="product"> <!-- loop content --> </mat-card>

A class named "product" will be used for any styling that cannot be achieved using flex-layout.

To make the mat-card containing the button the same height as the products, apply some CSS:

.product{
  min-height: 250px;
  margin-bottom: 25px; /* equal to fxLayoutGap for even spacing */
  
  /* additional styling */
}

Note that with the min-height approach, your button may appear smaller than the products if the product cards exceed 250px in height.

If you want the button to always match the height of the products, use

fxLayoutAlign="center stretch"
instead of
fxLayoutAlign="center center"
, but all mat-cards will adjust in height based on the window width, which may not be desired.

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

A miniature triangle-shaped bubble crafted with 1px of CSS3 styling

Currently, I am experimenting with CSS3 and creating bubble shapes. However, I have encountered an issue. I am trying to create a triangle with a 1px border, but the result is a thicker triangle than desired. You can view my code on this fiddle : FIDDLE ...

Steps for connecting to a property in another component

As a newcomer to Angular, I am exploring new concepts for the first time. I have a custom component called Timeselector with an Apply button whose enable/disable state is determined by validations performed in another custom component called Monthpicker. C ...

Troubleshooting problem with aligning grid items at the center in React using

I've been facing a challenge in centering my elements group using the material ui grid system. Problem: There seems to be excess margin space on the extreme right. Code snippet: const renderProjects = projects.map(project => ( <Grid item ...

Creating a Cancel Button in JSP/HTML/JS/CSS Form: A Step-by-Step Guide

It is necessary to incorporate the functionality of "save" and "cancel" in the JSP code for this particular form. By selecting "save", the data entered into the form will be submitted to its intended destination. Alternatively, choosing "cancel" will dismi ...

Does the Sass default compiler have built-in autoprefixing capabilities?

Suppose I have the following sample code: :fullscreen a { display: flex; } Is it possible for the default sass compiler to transform it into this: :-webkit-full-screen a { display: -webkit-box; display: flex; } :-moz-full-screen a { display: fle ...

I am having trouble getting my footer to align properly in a vertical position

My goal is to have my li elements remain on the same line, but unfortunately, they are not cooperating (they are aligning horizontally, but that's all). Here is the code snippet: <footer> <div class="container"> <div id="coi ...

Unable to extend the data-toggle dropdown to the entire width of the screen

Is there a way to make my navbar dropdown menu expand to the full width of the screen without leaving white space on the left side? I am using Bootstrap and have included a media query in my CSS as shown below. https://i.sstatic.net/US3ce.png <nav clas ...

The parameter type '{ src: string; thumb: string; }' cannot be assigned to the 'never' type in the argument

Sample Typescript Code: I am experiencing issues with my code and cannot comprehend this error message- Argument of type '{ src: string; thumb: string; }' is not assignable to parameter of type 'never' _albums = []; constructor( ...

Overflow: Truncating text with an ellipsis in the center

Seeking a CSS-only solution for adding an ellipsis in the middle of a string when it exceeds its container. I have tried splitting the container in half, trimming the first half with a wrapper on a whole letter and adding an ellipsis to the front of the s ...

Keep track of the input values by storing them in an array after they are

Creating an Angular application to read barcodes. barcode-scanner.component.html <form #f="ngForm" class="mt-3 text-center" id="myform" (ngSubmit)="onSubmit(f)"> <div class="text-center"> <input type="text" maxlength= ...

Transforming the timestamp to a date object using Angular and Typescript

As a newcomer to Angular 2.0, I've been delving into new concepts in order to grasp it better. However, despite encountering this common issue multiple times and reading through various solutions, I haven't been able to find the answer to my prob ...

Including a Javascript library (jsencrypt) in an Angular 2 application

I have gone through countless tutorials on this particular issue, but unfortunately, I have not yet found a solution. Let me provide some context first. I am working on an Angular 2 application and I need to incorporate this JS library for encryption: http ...

Animating changes on a webpage using CSS transitions in conjunction with the

Can the border color of a simple line div be changed from top to bottom using GreenSock? .line { position: relative; border: 1px solid #c3ced8; width: 0; height: 50px; display: block; content: ''; z-index: 1; top: -19px; marg ...

Ways to initiate update notification when altering an array object?

I am working on my Angular4 app and I have a component that uses a *ngFor directive to iterate over an array: <div *ngFor="let person of persons"> {{person.name}} {{person.car}} </div> Within the same component, there is a feature to ...

The global class variable encounters an error when trying to assign the value of "socket" to it

Within my class constructor, I am setting up a Socket connection and then storing the socket parameter in a global class variable (this.socket_variable = socket) so that I can access it across all functions in the class. CODE const { Server } = require(&q ...

Incorporating rounded corners to an embedded YouTube video

Check out this JSFiddle link. The border-radius property appears to be working correctly at first, but then the rounded corners suddenly disappear shortly after loading. Is there a way to apply rounded corners to YouTube videos that are embedded on a webp ...

CSS Techniques for Smooth Transitions

When the hamburger icon is pressed, a menu appears over the current page with CSS from Glamor. The menu slides in perfectly from the right side of the screen, but I am having trouble getting it to slide out when any part of the menu is clicked. I have def ...

Unlimited rotation - using setInterval function

I am encountering an issue with removing the move class from my code. Can someone please check it out for me? let lis = document.querySelectorAll('li') let arr = []; for (let i = 0; i < lis.length; i++) { arr.push(lis[i]); } setInterval( ...

The issue with making an HTTP POST request in Angular 2

Service: postJson() { var json = JSON.stringify({ "key": "CT", "values": ["FSP", "HMC", "PHYP","hell"] }); let headers = new Headers({'Content-Type':'application/json'}); //let options = new RequestOptions({ ...

Let's compare the usage of JavaScript's toUTCString() method with the concept of UTC date

When I fetch the expiry date time in UTC from the Authentication API along with a token, I use the npm jwt-decode package to extract the information. private setToken(value: string) { this._token = value; var decoded = jwt_decode(value); this._ ...