Using <template is="dom-if" with a condition
Asked Answered
M

3

10

I have a <template is="dom-if" if=... that I want to use with a logical condition.

Any binding I try appears to be truthy:

<link href="https://polygit.org/components/polymer/polymer.html" rel="import">

<dom-module id="test-thing">
  <template>
    <template is="dom-if" if="{{title == 'foo'}}" restamp>
      Title is <b>FOO</b>
    </template>
    <template is="dom-if" if="{{title}} == 'bar'" restamp>
      Title is <b>BAR</b>
    </template>
    
    Actual: "{{title}}"
  </template>
  <script>
    Polymer({
      is: 'test-thing',
      properties: {
        title: {type: String,value:''}
      }
    });
  </script>
</dom-module>

<div>
  Title: foo<br>
  <test-thing title="foo"></test-thing>
</div>
<div>
  Title: bar<br>
  <test-thing title="bar"></test-thing>
</div>
<div>
  Title: abc<br>
  <test-thing title="abc"></test-thing>
</div>

What is the correct way to apply an if condition to a dom-if template?

Mccahill answered 18/4, 2017 at 9:30 Comment(0)
E
21

you have to define your function.

<template is="dom-if" if="[[_isEqualTo(title, 'Foo')]]">

and then in script:

function _isEqualTo(title, string) {
  return title == string;
}

whenever is property title changed, function _isEqualTo is called. so you don't have to take care of observing property or something.

function _isEqualTo is called with 2 parameters, the second one is just plain string you want to compare some value with.

Ezequieleziechiele answered 18/4, 2017 at 9:35 Comment(3)
Thanks Kuba - I realise that I can wrap the condition in a function or add a property that is set when the related property are changed, but is that really the only way? It feels very clunky to extract away a function just so that an if block can evaluate the if.Mccahill
there is no other way. You can use computed, or observer options of property also. But there isn't anything like {{title == 'foo'}}. You have to get used to it. I was using handlebars before Polymer and it was really annoying for me at the beginning, so i know how you feel about it :D .Pious
typo '_isEuqalTo'Incommunicado
B
4

The only logic you can use in a binding is not. for instance:

<template is="dom-if" if="{{_isEqualTo(title, 'Foo')}}">
<template is="dom-if" if="{{!_isEqualTo(title, 'Foo')}}">
Batista answered 20/4, 2017 at 7:55 Comment(0)
F
1

If your data was such that Foo was boolean or had an attribute that "Foo":true or "isFoo":true . Then you could just do:

<template is="dom-if" if="{{isFoo}}">
   Foo
</template>
Factious answered 26/9, 2017 at 22:32 Comment(1)
The problem is that when the underlying property is changed, the template won't get updated to reflect that change, so the isFoo is not re-evaluated. You have to specify the underlying property as well, as in the other answers is shown. So your solution is not working well.Orchidaceous

© 2022 - 2024 — McMap. All rights reserved.