What is the best way to adjust the bootstrap column size using variables and decide when to insert a new row dynamically?

I am struggling to dynamically change the number of columns in a row based on the already sorted array. I want the layout to look like the example at the bottom, with Comedies spanning two rows, Action spanning three, and Horror only one row. However, I can't seem to figure out how to achieve this using Typescript.

  var movies = [
    { title: 'movie 1', genre: 'comedy' },
    { title: 'movie 2', genre: 'comedy' },
    { title: 'movie 3', genre: 'action' },
    { title: 'movie 4', genre: 'action' },
    { title: 'movie 5', genre: 'action' },
    { title: 'movie 6', genre: 'horror' }
  ];
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

<div *ngFor="let movie of movies; let index = index">
  <div class="form-row">
    <div class="col">{{movie.title}}</div>
  </div>
</div>

<div class="form-row">
  <div class="col-3">Movie 1</div>
  <div class="col-3">Movie 2</div>
  <div class="col-3">Movie 3</div>
</div>
<div class="form-row">
  <div class="col-6">Movie 4</div>
  <div class="col-6">Movie 5</div>
</div>
<div class="form-row">
  <div class="col-3">Movie 6</div>
</div>

Answer №1

Include an array of genres in your component

genres = ['action', 'comedy', 'horror']
// If dynamic, fetch from movies

Then, in your template, you can iterate over genres and movies like so:

<div class="form-row" *ngFor="let genre of genres>
    <ng-container *ngFor="let movie of movies;">
        <div *ngIf="movie.genre === genre"
        [ngClass]="{'col-3': genre !== 'action', 'col-6': genre === 'action'}">
        {{movie.title}}
        </div>
    </ng-container>
</div>

[ngClass] allows you to apply a class to an element based on a specific condition

It is used here to contain the ngFor directive because ngFor and ngIf cannot be used in the same element.

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

Angular 10 Reactive Form - Controlling character limit in user input field

I'm currently developing an Angular 10 reactive form and I am looking for a way to restrict the maximum number of characters that a user can input into a specific field. Using the maxLength Validator doesn't prevent users from entering more chara ...

Ready to Opt-Out in RxJS 6?

My test is functioning properly at the moment, but changing the active value causes it to break. Therefore, I am looking to unsubscribe a (which is the current active Observable) before proceeding with any other tests: let a:Observable<Todo> = store ...

Is it possible that an error is triggered when utilizing canActivate or canChildActivate?

A problem has arisen while using canActivateChild or canActivate in the child route. Despite working fine previously, an error is now being thrown: ERROR in src/app/app-routing.module.ts(8,7): error TS2322: Type '({ path: string; redirectTo: string; ...

What is the purpose of manually creating the vscode.d.ts file in the vscode source code?

Manually writing .d.ts files is typically only necessary when working with existing .js files. If you're developing a TypeScript project, it's recommended not to write .d.ts files by hand, as the compiler with the --declaration option can auto-ge ...

Navigating with additional parameters using ? and & symbols

I've been struggling to understand how Angular's routing system works, but so far I haven't been successful. My goal is to extract all the parameters from a URL using Angular's route functionality. Let's consider this example URL: ...

The communication between Angular and Unity using SignalR for messaging is not functioning properly, as I am unable to

Trying to establish a connection between Angular and Unity has been challenging for me. I can't seem to get them to communicate with each other. My goal is to have Angular "announce" when someone enters a room, and have Unity "greet" the user enterin ...

various positions for ngb properties

My input field has both a tooltip and a dropdown attached to it using the ngb attributes: <input placement="right" ngbTooltip="Search" [ngbTypeahead]="search" /> The issue I'm facing is that I want the tooltip to appear on the right ...

Using the useEffect hook with Redux-Toolkit dispatch causes an endless cycle of execution

Issue I am encountering an infinite loop problem when using useMutation from react-query to make post requests, retrieve user information from JSON, and then store it in my redux store using useEffect based on the status provided by the useMutation hook. ...

Tips for identifying the load window in Ionic 2 RC3 Angular 2

In the various services that I am using, I implement a method to load content. Each service has its own loadController to display a loading window. How can I detect if a loading window already exists in order to prevent showing a new one? *Please note: I ...

What is the best way to parse JSON data with Typescript?

I am dealing with JSON data structured as follows: jsonList= [ {name:'chennai', code:'maa'} {name:'delhi', code:'del'} .... .... .... {name:'salem', code:'che'} {name:'bengaluru' ...

Optimizing your use of fromCharCode.apply with Uint8Array in TypeScript 3

I recently came across some code that I inherited which appears like this: String.fromCharCode.apply(null, new Uint8Array(license)); Recently, we updated our project dependencies to TypeScript 3, which raised an error stating: Argument of type 'Ui ...

What is a more efficient method for incorporating optional values into an object?

Currently, I am utilizing the optional addition feature in this way: ...(!!providerId && { providerId }), ...(!!practiceId && { practiceId }), Is there a more elegant shorthand method to replace this logic, such as: yield createRemark ...

What is the best way to trigger a new api call after the previous one has successfully completed?

I'm just starting to learn about Angular and RxJS, and I have a specific scenario that I'm struggling with. I need to make a new API call after a previous one is successfully resolved within the Angular/RxJS context, but I'm not sure how to ...

What sets property binding with methods in Angular apart from using @Output() and EventEmitter?

Consider a scenario where I have a set of parent-child components in Angular structured like this: Child component class: export class ChildComponent { @Input() addTask:any; } Child component template: <button (click)="addTask('cleaning&a ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

What sets apart the states of the select tag from other input tags in Angular?

I am having trouble displaying an error message for a select tag when it is in a touched state. The error handling seems to be working fine for other input tags, but not for the select tag. Below is the code snippet: <div class="form-g ...

Utilizing logical operators to assign values to variables in Typescript

export class SearchResult { id: string; constructor(obj?: any) { this.id = obj && obj.id || null; } } Can someone explain to me the meaning of obj && obj.id || null? I'm confused by this syntax. ...

When running scripts, Protractor is unable to perform a click action in Safari, even though it works perfectly in

Currently, I am in the process of developing an angular application and utilizing directconnect for Chrome and Firefox. All my test scripts are functioning as expected, however, a new requirement has been introduced to run these same tests on Safari. To ...

Ensuring version consistency across package.json files in an Angular library project

Is there an effortless way to ensure that the main package.json file and the library application's package.json file have matching versions when utilizing npm version commands during the construction of an Angular Library application? Currently, only ...

When incorporating a second overload as an object, it is generating a pair of errors

I'm currently working on creating an overload function that takes either two arguments or one argument as an object, which will be used in the following way: // Two parameters obj.set('a', '123'); obj.set('b', 'efg&a ...