How do I write condition in polymer1.0 with “dom-if”?

让人想犯罪 __ 提交于 2019-12-10 04:04:55

问题


I have below code:

<template is="dom-if" if="{{item.hasAttach}}">
     <i class="fa fa-paperclip"></i>
</template>

item.hasAttach = true/false

But I want to check condition in this if like : item.content_format_code == 'PDF'

<template is="dom-if" if="{{item.content_format_code == 'PDF'}}">
         <i class="fa fa-pdf"></i>
    </template>
<template is="dom-if" if="{{item.content_format_code == 'JPEG'}}">
         <i class="fa fa-jpg"></i>
    </template>
<template is="dom-if" if="{{item.content_format_code == 'xls'}}">
         <i class="fa fa-xls"></i>
    </template>

it should be like {{item.content_format_code == 'PDF'}} = true/false But it is not testing this. I want to show icon as per file type. item.content_format_code == 'PDF' this is not checked true/false. In polymer it takes only true/false as a conditional actual value but don't check expression. Please Help me.


回答1:


You can use computed bindings.

Define a function that computes the expression and bind it to the dom-if.

<template is="dom-if" if="[[isFormat(item.content_format_code, 'PDF')]]">
     <i class="fa fa-pdf"></i>
</template>

Polymer({
    is: "my-element",
    isFormat: function(code, format) {
        return code === format;
    }
});



回答2:


Currently, polymer only supports simple constructs for conditions. This means that you can't write something like

[[ item.something == 'CONDITION' ]]

You are left with 2 choices:

  1. The item used for the condition is a boolean, than simply writing

    [[ item ]]
    

    or

    [[ !item ]]
    

    will work. The only operator you can use is '!'

  2. With more complex conditions, use computed bindings:

    [[ _computeResult(item) ]]
    



回答3:


I just did something similar and if you have access to your data it is much easier to just have a list of booleans like "is-PDF, is-JPG, is-PNG". Then you can just do;

<template is="dom-if" if="[[item.is-PDF]]">

That is what I ended up doing.



来源:https://stackoverflow.com/questions/32069770/how-do-i-write-condition-in-polymer1-0-with-dom-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!