Polymer 1.x: How to data bind to a variable boolean attribute?

人盡茶涼 提交于 2019-12-13 02:00:32

问题


Question

How do I bind a variable to/as the disabled attribute of a <paper-checkbox> element?

Based on the results of my code, it looks like the only way to toggle the disabled property is to include the disabled attribute as a string in the start tag. Surely there must be a way to toggle that as a variable?

Link to JSBin

http://jsbin.com/zecidojizu/edit?html,output
<!DOCTYPE html>
<html>  
<head>
  <meta charset="utf-8">
  <title>Polymer Bin</title>
  <base href="http://element-party.xyz/">
  <script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="all-elements.html">
</head>
<body>
<x-element></x-element>
<dom-module id="x-element">
  <template>
    <style>
      paper-checkbox {
        display: block;
        margin-bottom: 30px;
      }
    </style>
    <paper-checkbox                  >A</paper-checkbox>
    <paper-checkbox  disabled        >B</paper-checkbox>
    <paper-checkbox xdisabled        >C</paper-checkbox>
    <paper-checkbox  disabled=true   >D</paper-checkbox>
    <paper-checkbox  disabled="true" >E</paper-checkbox>
    <paper-checkbox  disabled=false  >F</paper-checkbox>
    <paper-checkbox  disabled="false">G</paper-checkbox>
    <paper-checkbox  [[bool]]        >H</paper-checkbox>
    <paper-checkbox "[[bool]]"       >I</paper-checkbox>
    <paper-checkbox  {{bool}}        >J</paper-checkbox>
    <paper-checkbox "{{bool}}"       >K</paper-checkbox>
  </template>
  <script>
    (function(){
      Polymer({
        is: 'x-element',
        properties: {
          bool: {
            type: String,
            value: 'disabled'
          }
        }
      });
    })();
  </script>
</dom-module>
</body>
</html>

回答1:


You need to bind the attribute like so: disabled=[[bool]]. This is the equivalent of calling element.disabled = bool where element is some instance of paper-checkbox.

See this forked JSBin for an example.

Basically a Boolean HTMLAttribute will be true if that attribute exists, and false if it does not exist. So for:

<paper-checkbox disabled="[[isDisabled]]"></paper-checkbox>

The output HTML will look like this:

<paper-checkbox disabled></paper-checkbox>

when isDisabled is true, and look like this:

<paper-checkbox></paper-checkbox>

when isDisabled is false.

That's why setting

<paper-checkbox disabled="false"></paper-checkbox>

will still make the checkbox disabled.

See the last paragraph in Polymer's Documentation on Attribute Deserialization




回答2:


disabled is a native HTML attribute. To bind to native attributes, you must use $= instead of =.

<paper-checkbox disabled$="{{isDisabled}}">Foo</paper-checkbox>



回答3:


Haven't you left out disabled$={{Boolean}}?



来源:https://stackoverflow.com/questions/33883824/polymer-1-x-how-to-data-bind-to-a-variable-boolean-attribute

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