Operator comparison in an *ngIf

2019-09-21 07:15发布

问题:

I want to compare number in an ngIf and depending on the result i'll display something.

  <div>
      <div *ngIf="number(user.number)>59">
     {{  number(user.number) }}
      </div>
      <div *ngIf="number(user.number)<60">
        {{  number(user.number) }}
        </div>
    </div>

my number.ts

 number ( date: Date) {
    const now = new Date().getFullYear()
    const diff = Math.abs(now - new Date(date).getFullYear())
    console.log(diff)
    return diff 
}

it will return a number

This is not working i think there's a problem with ">" & "<" operator, is there a way to make it work ?

回答1:

the interior of *ngIf (value between "") must end up in being evaluable to truthy/false value. The issue might be in your number() implementation, usages of > & < are perfectly fine.

Please provide your function implementation and wider context i.e. from where user.number comes from

--EDIT--
After OP posted TS code, there will be issue with date format. The part: new Date(date).getFullYear() in case of incorrect value will evaluate to 1970, then result will be always 48, which is less than both values compared. You need to validate your input in date creation.

Try in browser console to create any of following:

new Date(99)
new Date(2000)
new Date(20)

they will all evaluate to Thu Jan 01 1970 01:00:00 GMT+0100. Supplement Date constructor with dummy parameter:

new Date(99, 0)
new Date(2000, 0)
new Date(20, 0)

to get valid dates. But still, this is just an assumption, since you are not providing us format of user.number, i just assumed this is input text value in range 0 to infinity.



回答2:

You can try with moment

install moment by - npm install moment --save

app.component.html

<div>
    <div *ngIf="number(user.number)>59">
        {{ number(user.number) }}
    </div>
    <div *ngIf="number(user.number)<60">
        {{ number(user.number) }}
    </div>
</div>

app.component.ts

import moment from 'moment';

number(date: Date) {
    const diff =Math.abs(moment().diff(moment(date),'year'))
    console.log(diff);
    return diff;
}


标签: angular