0

This is angular app, I want to apply css class based on condition that char length of variable is greater than 128 char. I was inspired by this post enter link description here. As shown below in the code snippets, I am trying to dynamically apply style based on condition that charlen value is within or outside 128. Please I am new to Angular and I am npot aware of many concepts, thnak you for suggestions.

template.html

<input [ngClass] = "(charlen <128)?'class1':'class2' />

template.ts

str:String;
charlen:Number;

ngInit () {
 str="this is not 128 char";
 charlen = str.length;
}

template.css

.class1 {
color:red;
}

.class2 {
 color:blue;
}
karansys
  • 2,449
  • 7
  • 40
  • 78

3 Answers3

4

You can do it like this :

<input [ngClass]="{ 'class1': charlen < 128, 'class2': charlen >= 128 }" />
Emilien
  • 2,701
  • 4
  • 15
  • 25
1

Using class with property binding, we can achieve the above

.html

<input [class] = "(charlen <128)?'class1':'class2'" />

.ts

str:String;
charlen:Number;

ngOnInit() {
  this.str= "this is not 128 char";
  this.charlen = this.str.length;
}
Gangadhar Gandi
  • 2,162
  • 12
  • 19
0

check this code

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

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

  str:String;
charlen:Number;

ngOnInit () {
 this.str="this is not 128 char";
 this.charlen = this.str.length;
}
}

and use same html code, it is working.

check working demo

Do let me know if you face any issue.

Piyush Jain
  • 1,895
  • 3
  • 19
  • 40