Angular Conditional in HTML does not like less than or greater than symbols

Viewed 52204

Simple question, cannot seem to find an answer... (this will be a quick 'point' for someone)

I'm looking to have a condition in an Angular 5 ngIf be "less than" some variable.

<div class="row" *ngIf="Subject < 4" >
<div class="row" *ngIf="Subject <= 4" >

this syntax bombs because "<" - how can I do this? (without having to write function)?

9 Answers

*ngIf doesn't work with '<=' sign. Need to check equal(==), less than(<) and greater than(>) conditions separately with OR operator.

<div class="row" *ngIf="Subject<4 || Subject==4" >
  Row 1 (Rendered when Subject is lesser than or equal to 4)
</div>
<div class="row" *ngIf="Subject>4" >
  Row 2 (Rendered when Subject is greater than 4)
</div>

Some IDE might show '<' or '>' sign in as syntax error while writing the code, because these are used for HTML tags also. But, it will not throw any compile or run time error.

Write a simple getter

<div class="row" *ngIf="greaterThan(Subject, 4)" >

component.ts:

public greaterThan(subj: Subject, num: number) {
  return sub < num;
}

The editor may pickup the < as an error. It's not actually an error in angular to use less than in an *ngIf. This is likely a red herring so look for the issue elsewhere.

In my case I had an issue with a null reference. E.G.

<span *ngIf="someArray">
  <span *ngIf="someArray.length < 3" class="keypadOutput">&nbsp;</span>
</span>

In some cases someArray can be null so I needed to add an outer *ngIf check for someArray.

Try this

<div class="row" *ngIf="Subject < 4 || Subject = 4" >

<div class="row" *ngIf="4 > Subject">
<div class="row" *ngIf="4 >= Subject">

And you're done Works perfect for me

I had the same problem with a similar template element,

<p *ngFor="let msg of logMessages"
[ngClass]="{greaterThan4Class: (rowCount > 4)}"
>
{{msg}}
</p>

, which caused an an html parser error after the build, and caused the app to crash in the browser. The parser interpreted the greater-than symbol in (rowCount > 4) as the close of the opened <p elemment. It seemed to be caused by TypeScript not being able to locate all the necessary types for Angular.

SOLUTION: add this setting to tsconfig.json:

    "typeRoots": [
      "node_modules/@types"
    ],

Note: after this change I was unable to reproduce the issue by removing the above. This might also be solved by performing [npm install] on the Angular project.

HTML code for less than i.e. &#60; can be used and it works. For example in your question, please try:

<div class="row" *ngIf="Subject &#60; 4" > <div class="row" *ngIf="Subject &#60;= 4" >

Just replace the ">" and "<" operators with their HTML encodings, "&gt;" and "&lt;", respectively:

<div class="row" *ngIf="Subject &lt; 4" >

<div class="row" *ngIf="Subject &lt;= 4" >
Related