简体   繁体   中英

Dynamic class assignment in Typescript

I'm working on my post-graduate assignment where I have to create a simple calculator. I'm almost there but the final element - making the negative result red and positive green is still missing. The result must be seen in an input field

I was trying to use [ngClass]= with two conditions but it is not working:

<input type="number" [ngStyle]="resultStyling" value="{{ result }}" name="resultInput" 
[ngClass]="{
  'red': <=0,
  'green': !<=0
  }">

the public classes in component.ts for the calculator are:

public field1: number;
  public field2: number;
  public result: number;
  public isPositive: boolean = true;

The HTML:

<input type="number" [ngStyle]="inputStyling" name="field1" [(ngModel)]="field1"><br>
<button (click)="add()" [ngStyle]="buttonStyling">+</button>
<button (click)="substract()" [ngStyle]="buttonStyling">-</button>
<button (click)="multiply()" [ngStyle]="buttonStyling" >*</button>
<button (click)="divide()" [ngStyle]="buttonStyling">/</button><br><input type="number" [ngStyle]="inputStyling" name="field2" [(ngModel)]="field2">
<br>=<br>
<input type="number" [ngStyle]="resultStyling" value="{{ result }}" name="resultInput">

And the CSS are just 2 simple classes `.red {color: red} and.green {color: green}.

I can't figure out how to make the result show in color. Do you have any suggestions what may be the solution? Maybe the [ngClass] should just be written in a different way?

The whole code may be also found on my stackblitz: https://stackblitz.com/edit/k-rapacz-angular-day1-z6vxu1

Thank you in advance for the support!

If you look at the angular documentation there are multiple ways to conditionally add a class:

In your case you can do:

<input [ngClass]="{'red': result < 0, 'green': result > 0}">

or

<input [class.red]="result < 0" [class.green]="result > 0">

if you want 0 to have a color too, you can also just do:

[ngClass]="result < 0 ? 'red' : 'green'"

working example

What about the class.my-class directive? It applies the specified class to the element only if the condition is met:

<input type="number" [ngStyle]="resultStyling" value="{{ result }}" name="resultInput" 
[class.red]="result <= 0" [class.green]="result > 0">

Styles may be applied in the below way using Ternary Operator.

In you html last input, you can add a ngClass and add the styles based on ternary operator.

<input type="number" [ngStyle]="resultStyling" [ngClass]="result>0 ? 'green' : 'red'" value="{{ result }}" name="resultInput">
<br>

I the above code, we are checking if result is greater than 0 and, if yes, the green class is applied else, the red class is applied.

You can read more about applying classes here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM