What is the best way to center vertically the angular + material mat-checkbox outside of a form group?

I am faced with two scenarios:

The first scenario involves using a FORM GROUP with Angular 5 and Angular Material Design.

Below is the code for handling multiple checkboxes:

<div *ngSwitchCase="'checkboxField'" class="checkbox-field">
  <div *ngIf="!field?.properties?.hideTitle">{{field?.properties.title}}</div>
    <div class="checkbox-label" *ngFor="let element of field?.elements">
         <mat-checkbox
        [value]="element?.properties.value"
        [disabled]="field?.properties.disabled"
        [checked]="isItemChecked(element?.properties.value)"
        (change)="onCheckboxChange(element?.properties.value);
        notifyFormOfChange($event);">
        {{element?.properties.title}}
    </mat-checkbox>
  </div>
</div>

The display can be in two formats:

1) HORIZONTAL 2) VERTICAL

The vertical layout only occurs when I have multiple checkboxes or radio buttons within a form-group (which also needs fixing). Without a form-group, the checkboxes or radio buttons are displayed in a line without space between them.

Vertical alignment of checkboxes is required when this property is set to true:

field.properties.stackVertically = true

This can only be achieved through CSS.

Here's the CSS style for the form-group:

.row[_ngcontent-c30] {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    margin-right: -15px;
    margin-left: -15px;
}

There is no specific styling for the horizontal layout.

Enabling the vertical option is conditional on the following:

field.properties.stackVertically = true

Refer to the image links below for visual examples:

https://i.stack.imgur.com/umwvj.png https://i.stack.imgur.com/kPA7m.png

UPDATE BASED ON A SUCCESSFUL SOLUTION!!!

Check out the success image and view the integrated solution from above with proper placement.

It turns out that the solution needed to be applied on the second line instead of where I initially thought. Some trial and error led to success!

https://i.stack.imgur.com/TauHQ.png

Below is the updated code with KimCindy's helpful answer included. Many thanks!

<div *ngSwitchCase="'checkboxField'" class="checkbox-field">
    ***<div class="cb-wrapper" [ngClass]="{'cb-vertical': field?.properties?.stackVertically }">***
         <div *ngIf="!field?.properties?.hideTitle">{{field?.properties.title}}</div>
      <div class="checkbox-label" *ngFor="let element of field?.elements">

           <mat-checkbox
          [value]="element?.properties.value"
          [disabled]="field?.properties.disabled"
          [checked]="isItemChecked(element?.properties.value)"
          (change)="onCheckboxChange(element?.properties.value);
          notifyFormOfChange($event);">
          {{element?.properties.title}}
      </mat-checkbox>
    </div>
  ***</div>***
</div><!--checkbox-->

Answer №1

If you're looking to style elements dynamically, consider using the ngClass directive.

Take a look at this example:

HTML:

<div class="dynamic-wrapper" [ngClass]="{'dynamic-vertical': !check }">
  <mat-checkbox>Option 1</mat-checkbox>
  <mat-checkbox>Option 2</mat-checkbox>
  <mat-checkbox>Option 3</mat-checkbox>
</div>

CSS:

.dynamic-wrapper {
  display: flex;
  flex-wrap: wrap;
  justify-content: left;
  flex-flow: row;
}

.mat-checkbox {
  margin-left:20px;
} 

.dynamic-vertical {
  flex-flow: column;
}

TS:

export class DynamicStylingExample {
  check: boolean = false;
}

Stackblitz Demo: https://stackblitz.com/edit/angular-addm8z?file=app%2Fcheckbox-overview-example.css

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 Angular 6 Share module functionality not functioning as expected

While creating my Angular 6 application, I encountered an issue with sharing a header across multiple pages. I tried including it but it doesn't seem to be working. Can anyone point out what I might be doing wrong? For a demonstration, you can visit . ...

Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically und ...

Is the async pipe the best choice for handling Observables in a polling scenario

The situation at hand: I currently have a service that continuously polls a specific URL every 2 seconds: export class FooDataService { ... public provideFooData() { const interval = Observable.interval(2000).startWith(0); return interval ...

Issue with routing in a bundled Angular 2 project using webpack

Having a simple Angular application with two components (AppComponent and tester) webpacked into a single app.bundle.js file, I encountered an issue with routing after bundling. Despite trying various online solutions, the routing feature still does not wo ...

Angular UI validation malfunctioning upon loading of the page

My webpage contains multiple rows with specific validation requirements - at least one Key, Time, and Input must be selected. Initially, the validation works as expected. However, after saving and reloading the page, the default selection for Key, Time, an ...

Guide on navigating to a specific page with ngx-bootstrap pagination

Is there a way to navigate to a specific page using ngx-bootstrap pagination by entering the page number into an input field? Check out this code snippet: ***Template:*** <div class="row"> <div class="col-xs-12 col-12"> ...

What could be causing the countdown timer to speed up unexpectedly?

Currently, I am developing a quiz application. At the moment, I need to implement the following features: Countdown timer Questions Question Choices The countdown timer for each question functions properly as long as the answer button is not clicked or ...

Angular's Async Pipe displaying outdated data

I am encountering an issue with my Angular async pipe setup. Here is the code snippet: <ng-container *ngIf="showProjects && (projects | async) as projectList; else loading"> In my projects.page.ts file, I have the following funct ...

Collaborate on sharing CSS and TypeScript code between multiple projects to

I am looking for a solution to efficiently share CSS and TS code across multiple Angular projects. Simply copy-pasting the code is not an ideal option. Is there a better way to achieve this? ...

Encountering a surprise token < while processing JSON with ASP.NET MVC alongside Angular

I encountered an issue when attempting to return the Index page. The data is successfully sent from the client to the server, but upon trying to display the Index page, an error occurs. Could someone review my code and identify where the mistake lies? acc ...

What are the steps to create a sliding carousel using ng2-bootstrap?

I've integrated the Angular2 Bootstrap carousel component from the following link: here, but I'm facing an issue with the transition and animation effects when sliding between items. Any suggestions on how to resolve this? ...

Subscribe to the service in Angular and make repeated calls within the subscription

What is the most effective way to chain subscriptions in order to wait for a result before starting another one? I am looking for something similar to async/await in Javascript, where I need the result of the first call to trigger the next one. Currently, ...

Access to Angular CORS request has been blocked

I'm currently working on establishing a connection between my Angular application and a basic REST server using express. The server responds to requests with JSON data exclusively. To enable CORS support, I've integrated the cors module from npm ...

Tips for hiding a sidebar by clicking away from it in JavaScript

My angular application for small devices has a working sidebar toggling feature, but I want the sidebar to close or hide when clicking anywhere on the page (i.e body). .component.html <nav class="sidebar sidebar-offcanvas active" id="sid ...

Exploring Computed Properties in Angular Models

We are currently in the process of developing an application that involves the following models: interface IEmployee{ firstName?: string; lastName?: string; } export class Employee implements IEmployee{ public firstName?: string; public l ...

Testing Angular components with Karma Server: An uncaught promise rejection occurred stating, "The code should be executed within the fakeAsync zone."

For my unit test development, I am utilizing karma. In some of my test cases, I have used fakeSync - tick() and promises. Although my tests are running successfully, there seems to be an issue with the karma server: my test.spec.ts : import { async, Co ...

Issue with running "ng generate" or "ng add" commands

While using angular version 8 in Termux Android ARM, I encountered an issue when trying to add the PWA and service worker to my website project. Here is the information about the angular version obtained from Angular CLI: $ ng version _ ...

Learn how to safely handle JSON vulnerabilities in Angular by removing the prefix ")]}'," from the JSON data

Our Webservice JSON output is designed to enhance security by starting with the prefix ")]}'," I have read several articles and learned that HttpClient offers libraries to remove this JSON prefix, but I'm struggling to find a proper example. I ...

Convert the XML response from an API into JSON

Is there a way to convert my XML response into JSON using Angular? This is the response I am working with: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://tempuri.org/"><?xml version="1.0" encoding="utf-8"?&gt; &lt;Fer ...

The version of Angular CLI on my local machine is newer than the global

I have been trying to set up a new Angular project using Angular CLI version 13.3.10. However, every time I create a new project, it ends up being in version 13.3.11. Prior to creating this project, I followed the steps of running npm uninstall -g @angula ...