使用自定义逻辑为paper-input-container设置默认值

时间:2016-08-18 11:04:27

标签: polymer polymer-1.0

我正在尝试重现聚合物演示here提供的社会安全号码示例。如何在纸张输入容器中设置ssn-input组件的默认/初始值?正在运行的版本为here

我尝试将属性值添加到paper-input-container和ssn-input,但它不会显示为初始默认值。

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Polymer Element Test Case</title>
  <base href="//polygit.org/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">

  <link rel="import" href="paper-input/paper-input-container.html">
  <link rel="import" href="paper-input/paper-input-error.html">
  <link rel="import" href="paper-input/demo/ssn-input.html">
</head>
<body>
   <paper-input-container always-float-label auto-validate attr-for-value="value">
          <label>Social Security Number</label>
          <ssn-input class="paper-input-input"></ssn-input>
          <paper-input-error>SSN invalid!</paper-input-error>
   </paper-input-container>
</body>
</html>

我检查了&lt; ssn-input&gt;的原始实现,在我看来,没有代码可以在三个子字符串中拆分提供的值并将其提供给三个纸张输入。相反,当用户在纸张输入中键入内容时,每个字符串变为_ssnX,computeValue函数将它们链接在一起,将结果存储在value属性中。这是来自ssn-input.html的代码:

properties: {
  value: { notify: true, type: String },
  _ssn1: { type: String },
  _ssn2: { type: String },
  _ssn3: { type: String },

  validator: { type: String, value: 'ssn-validator' }
},
observers: [
  '_computeValue(_ssn1,_ssn2,_ssn3)'
],
_computeValue: function(ssn1, ssn2, ssn3) {
  this.value = ssn1.trim() + '-' + ssn2.trim() + '-' + ssn3.trim();
}

1 个答案:

答案 0 :(得分:0)

ssn-input是读取用户输入的内容并将所有内容放入value属性的组件。因此,首先要初始化此元素的value属性,如下所示:

<paper-input-container always-float-label auto-validate>
    <label>Social Security Number</label>
    <ssn-input class="paper-input-input" value="102-12-1233"></ssn-input>
    <paper-input-error>SSN invalid!</paper-input-error>
</paper-input-container> 

属性值初始化ssn-input中的相关属性。 ssn-input有三个内部input元素,用于显示和获取用户输入。因此,必须在&#34; - &#34;上分割初始值。字符。最好的地方是value属性观察者。因此,修改后的ssn-input元素代码如下:

Polymer({
  is: 'ssn-input',

  behaviors: [
    Polymer.IronValidatableBehavior
  ],

  properties: {
    value: { notify: true, type: String, observer: '_handleValueChanged' },
    _ssn1: { type: String },
    _ssn2: { type: String },
    _ssn3: { type: String },
    validator: { type: String, value: 'ssn-validator' }
  },

  _handleValueChanged: function(value) {
    var arr = value.split("-");
    this._ssn1 = arr[0];
    this._ssn2 = arr[1];
    this._ssn3 = arr[2];
  },

  observers: [
    '_computeValue(_ssn1,_ssn2,_ssn3)'
  ],

  _computeValue: function(ssn1, ssn2, ssn3) {
    this.value = ssn1.trim() + '-' + ssn2.trim() + '-' + ssn3.trim();
  }
});

这里是jsbin running example