Home > Net >  How to Align all elements inside a class with boolean condition in Angular?
How to Align all elements inside a class with boolean condition in Angular?

Time:09-29

HTML

<html lang="en">
  <body>
    <div >
      <input  [ngClass]="{ 'first': !checked , 'new-first' : checked}">
      <input  [ngClass]="{ 'first': !checked , 'new-second' : checked}">
    </div>
    <div>
    <mat-checkbox [(ngModel)]="checked"></mat-checkbox>
  </div>
  </body>
</html>

CSS

p {
  font-family: Lato;
}

.parent {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  gap: 10px;
  margin-top: 50%;
}
.first {
  float: left;
  padding: 10px;
  width: 50%;
}
.second {
  float: left;
  padding: 10px;
  width: 50%;
  margin-left: 45%;
}

.new-first {
  background-color: blue;
  float: left;
  padding: 10px;
  width: 50%;
}
.new-second {
  background-color: brown;
  float: left;
  padding: 10px;
  width: 50%;
}

COMPONENT TS

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular '   VERSION.major;

  checked:boolean = false;
}

I have two input fields column wise, and i have one checkbox, if i check the checkbox it becomes true so with the help of [ngClass] create a new class, so if it true alignment of the div is same, if it false then go to previous position, but its not working.

here is the stackblitz example link https://stackblitz.com/edit/angular-ivy-cnevqu?file=src/app/app.component.ts

example image one, example image two

CodePudding user response:

What you missed was that you tried to assign to the first input, which made it static. All you need is [ngClass]="expression ? 'true-class' : 'false-class' ".

app.component.html

<div >
  <input [ngClass]="checked ? 'new-first' : 'first'">
  <input [ngClass]="checked ? 'new-second' : 'second'">
</div>

<mat-checkbox [(ngModel)]="checked"></mat-checkbox>

As for the css, you shouldn't use float. You should use align-self if you want to align the inputs to the left or right of the parent div.

When the checkbox is false (not checked), first and second class is applied, so the inputs align to left and to the right respectively.

When the checkbox is true, the new-first and new-second class is applied. Because the parent class has align-items: center, both inputs automatically got centered.

app.component.css

.parent {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.first {
  align-self: start;
  padding: 10px;
  width: 50%;
}

.second {
  align-self: end;
  padding: 10px;
  width: 50%;
}

.new-first {
  background-color: blue;
  padding: 10px;
  width: 50%;
}

.new-second {
  background-color: brown;
  padding: 10px;
  width: 50%;
}
  • Related