Angular material chips showcase a row of five chips

I am working with the basic mat-chips from angular material and I want to arrange them in rows of five without increasing their size:
Chip1 Chip2 Chip3 Chip4 Chip5 ..................(space left)
Chip6 Chip7 Chip8 Chip9 Chip10 ...............(space left)
Chip11 Chip12 ....................................................(space left).

I need the chips' sizes to remain consistent at all times. Can this be achieved using flexbox? This is what I have tried so far: HTML:

<div class='list'>
   <mat-form-field class="example-chip-list" appearance="fill">
  <mat-label>Favorite Fruits</mat-label>
  <mat-chip-list #chipList aria-label="Fruit selection">
    <mat-chip *ngFor="let fruit of fruits" id='item' (removed)="remove(fruit)">
      {{fruit.name}}
      <button matChipRemove>
        <mat-icon>cancel</mat-icon>
      </button>
    </mat-chip>
  </mat-chip-list>
</mat-form-field>
</div>

CSS:

.list{
 width: 100%;
 flex-flow: row wrap;
}

#item{
flex: 1 0 20%; //I've attempted this, but it's not working as the chip sizes are still expanding to fill the div
}

Answer №1

It seems like achieving this using just CSS may be a challenge at the moment (although I could be mistaken). If all your chips are uniform in size, you might consider utilizing a CSS grid layout, but it appears that is not the case here. A possible solution would involve adding an additional HTML element every N items (in this scenario, every 5 items) to force the line break.

To implement this, you would need to reposition the *ngFor directive to a higher level (utilizing ng-container to avoid generating extra markup) and use its index to determine when to insert the additional item after every 5th chip:

<div class="list">
  <mat-form-field class="example-chip-list" appearance="fill">
    <mat-label>Favorite Fruits</mat-label>
    <mat-chip-list #chipList aria-label="Fruit selection">
      <ng-container *ngFor="let fruit of fruits; let idx = index;">
        <mat-chip id="item" (removed)="remove(fruit)">
          {{fruit.name}}
          <button matChipRemove>
            <mat-icon>cancel</mat-icon>
          </button>
        </mat-chip>
        <br class="breaker" *ngIf="(idx+1)%5===0" />
      </ng-container>
    </mat-chip-list>
  </mat-form-field>
</div>

I opted for the <br/> tag as it aligns with semantics, but feel free to choose otherwise.

Simply style the .breaker class accordingly:

.breaker {
  width:100%;
  content: '';
}

You can find a functional StackBlitz demo here.

Please note that this solution lacks responsiveness - for instance, if 5 chips cannot fit on a single row. However, considering your specific requirement of 5 chips per row, it doesn't leave much room for responsive design. It could be possible to adapt the layout dynamically by measuring the rendered chips and adjusting them on-the-fly through scripting, but this would require further exploration based on the project's demands.

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

What strategies can be implemented to restrict certain users from accessing specific components by manually altering the URL in Angular 2?

I am currently using Angular 2 to create a data table for displaying information. I have implemented a click event that redirects users to '/viewOutgoing;id=data_id', with the id corresponding to the data's id in the table. However, I need t ...

Parsing difficulties encountered: the element 'ion-col' is unrecognized

As I strive to develop Ionic 4 applications, a new error continues to surface even after attempts to resolve the previous one. Following the creation of a custom component mentioned in this error (How to load other page inside of an ionic segment?), a new ...

An issue was encountered at node_modules/@fullcalendar/core/main.d.ts(1196,54), error TS1144: Expecting either '{' or ';'

When attempting to execute npm run build in my project, I encountered the following error: ERROR in node_modules/@fullcalendar/core/main.d.ts(1196,54): error TS1144: '{' or ';' expected. node_modules/@fullcalendar/core/main.d.ts(1197,34 ...

Insert the META tag data specific to Facebook Instant Articles directly within the JavaScript code

My website is running on a custom-built CMS provided by a company, and it seems like a modified version of WordPress. They are unwilling to include a basic meta tag in our HTML code. I am looking for guidance on how I can incorporate Facebook's Insta ...

Creating an array by extracting form values in Angular

In my component, I have the following function: updateInfo(info: NgForm) { const changedValues = Object.keys(info.controls) .filter(key => info.controls[key].dirty === true) .map(key => { return { control: key, value: info.co ...

Enhance webpage speed by enabling browser caching for embedded iframe CSS and Javascript files

Imagine having a file named main.html. Inside this file, there's an iframe that points to another file called sub.html. Additionally, there's a button on main.html that, when clicked, refreshes the content of sub.html. This sub.html file relies o ...

Using the `npm install -g @angular/cli` command will not actually install the Angular CLI

I've set out to create a sample Angular2 web app, starting with the installation of Node.js (v 7.1.0) and NPM (v 3.10.9). However, when I try to install Angular CLI by executing 'NPM install -g @angular/cli' in the system command prompt, I e ...

Switching Angular fxLayout from row to column based on a conditional statementHere is an explanation of how to

Visit this link for more information Is there a way to set direction based on a specific value? <div if(value) fxLayout='row' else fxLayout='column'> ...

What causes IE11 to sporadically run inappropriate media queries?

My website has been displaying incorrectly on IE11 due to a media query being executed for widths less than 767px, even though the window width is actually more than that. Interestingly, this issue only occurs randomly and never when the debug window is op ...

"Troubleshooting: Why is :last-child not applying styles to my final

I'm encountering an issue in my example where the last </li> doesn't display properly when using :last-child. In the provided code, you can observe that when I target the last element with the class "aa," it shows the "+ Add" text. &.a ...

Webpack is failing to recognize certain CSS files

My development stack includes Vue.js 2.5.15, Webpack 4.12.0, css-loader 0.28.11, ASP.Net Core 2.1 in Visual Studio 2017. Starting with the Visual Studio asp.net core template project for Vue and Typescript, I prefer to have individual small CSS files with ...

Issue with triggering blur event in Internet Explorer while using Angular 2+

The issue discussed in the Blur not working - Angular 2 thread is relevant here. I have a custom select shared component and I am attempting to implement a blur event to close it when the component loses focus. // HTML <div (blur)="closeDropDown()" t ...

ERROR: The variable countryCallingCode has not been defined

I encountered an error when attempting to assign a value to my property countryCallingCode, which does not exist in the first option. this.allData.customerFacingPhone.countryCallingCode = newItem.countryCallingCode The error message I received was: ERROR ...

Setting up nginx docker image to host an angular application while also enabling page refresh is a straightforward process. Here

After reviewing numerous instances of individuals suggesting to simply paste location / { try_files $uri $uri/ /hockey/index.html =404; } or location / { try_files $uri $uri/ /index.html =404; } ...or experimenting with different ...

Easily retrieve the value of a form control when it is changed with Form

Currently, I am in the process of reviewing Formly. In my initial attempt, I am trying to trigger a method when the content of a textarea changes. The code snippet below shows what I have tried so far. Unfortunately, it seems like the functionality is no ...

The current code lacks any form of line breaks

While attempting to edit a CSS file in Sublime Text 2, I noticed that all the code is displayed without any line breaks. This makes it difficult to read and work with. Is there a way to fix this issue and format the code into readable sections? ...

What is the best method for sorting through observable data pulled from an API?

public data$: Observable<any[]>; ngOnInit(): void { this.data$ = this.InventoryService.getAllProducts(); } searchProducts(event: any) { let searchTerm: string = event.target.value; console.log(searchTerm); this.data$.pipe( ...

What is the best way to save a string for future use in Angular after receiving it from a POST request API?

I have been assigned to a project involving javascript/typescript/angular, even though I have limited experience with these technologies. As a result, please bear with me as I may lack some knowledge in this area. In the scenario where a user logs in, ther ...

What is the best way to position the logo in the center of the navigation bar, considering there are an unequal number of menu items on each side

As I work on coding a design I found for practice, I am facing the challenge of getting the logo to be centered in the navbar, similar to the layout in the Dribble link below. View Design on Dribble The navigation bar has 4 items aligned on the left and ...

Differentiating between inline and block elements in HTML5

Can you explain the various categories of inline and block elements in html5? I'm having trouble distinguishing between the different types of inline and block elements in html5. ...