javascript - double not (!!+) 的 Angular2 模板问题

标签 javascript templates angular

几个小时以来我一直在为这个问题苦恼,但现在我很确定这是 Angular2 的某个地方的问题。

场景:我从我的 PHP 中获取 JSON 中的 tinyint "isLiked": "1" .由于 JSON,Javascript 将 tinyint 理解为字符串而不是 bool 值,所以我一直在使用 good ol' !!+isLiked将其更改为 bool 值。

在我的 Angular2 模板中我需要做的:

<i class="glyphicon {{ (!(!!+post.isLiked) ) ? 'glyphicon-heart-empty' : 'glyphicon-heart' }}"></i>

这段代码曾经在带有 Underscore 模板的 Backbone 中完美运行。但是,Angular2 似乎做了一些改变 !!+"0"评估方式的事情!

在 Chrome 控制台中: !!+"0"返回 false .

在 Backbone +下划线中: <% !!+"0" %>在模板中显示 false .

在 Angular2 中: {{ !!+"0" }}在模板中显示 true .

这是它的 Playground http://plnkr.co/E3YGYeQ5ZZIRh8JxsUN6 .

false来自一个简单的 Javascript document.write(!!+"0")在 index.html 中,在 Angular 执行任何操作之前。

true在里面src/app.ts模板。

我错过了什么吗?

最佳答案

Angular 模板语法不支持完整的 JavaScript 语法。 只需将您的代码移动到一个函数中并调用它即可

<i class="glyphicon  {{ truthyCheck(+post.isLiked) ? 'glyphicon-heart-empty' : 'glyphicon-heart'  }}">
class MyComponent {
  trutyCheck(value):boolean {
    return !(!!+post.isLiked) ;
  }
}

Plunker example

另见
- https://angular.io/docs/ts/latest/guide/template-syntax.html#!#template-expressions
- https://angular.io/docs/ts/latest/guide/template-syntax.html#!#template-statements

关于javascript - double not (!!+) 的 Angular2 模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36303715/

相关文章:

javascript - Spotify web api 不适用于 ios 设备

javascript - 将 , 替换为 <br>

javascript - 向下滚动到内容而不更改页面 URL

C++ 类声明和命名空间

javascript - Angular 4.3.3 HttpClient : How get value from the header of a response?

javascript - 我怎样才能让我的轮播在 Angular 8 中工作

javascript - 如何向List.js添加另一个过滤类别?

javascript - 无法读取未定义的属性 'Symbol(Symbol.iterator)'

forms - Symfony 和简易管理 : How to apply easyadmin template to custom form

javascript - Angular2 : template work, 但 templateUrl 不是