聚合物纸输入错误图标

Polymer paper input error icons

Polymer 0.x 有一个组件 paper-input-decorator,其中,如果 paper-input 有错误,错误消息将显示一个图标。以下是paper-input-decorator中的代码。

<div class="footer" layout horizontal end-justified>
      <div class="error" flex layout horizontal center hidden?="{{!isInvalid}}">
        <div class="error-text" flex auto role="alert" aria-hidden="{{!isInvalid}}">{{error}}</div>
        <core-icon id="errorIcon" class="error-icon" icon="warning"></core-icon>
      </div>
      <div aria-hidden="true">
        <content select=".counter"></content>
      </div>
    </div>

Polymer 1.x 有一个元素 paper-input-error 可以用来显示错误信息。但是有没有办法在需要时为此添加图标?

您可以使用 <paper-input-container> 重新创建一个 <paper-input>,其 <paper-input-error> 中有一个图标。当输入为非数字时,以下 Polymer 元素模板在 <paper-input-error> 内显示错误图标:

<template>
  <style>
    :host {
      display: block;
    }

    /* In 1.x, the <input> is distributed to paper-input-container, which styles it.
    In 2.x the <iron-input> is distributed to paper-input-container, which styles
    it, but in order for this to work correctly, we need to reset some
    of the native input's properties to inherit (from the iron-input) */
    iron-input > input {
      @apply --paper-input-container-shared-input-style;
      font-family: inherit;
      font-weight: inherit;
      font-size: inherit;
      letter-spacing: inherit;
      word-spacing: inherit;
      line-height: inherit;
      text-shadow: inherit;
      color: inherit;
      cursor: inherit;
    }
  </style>

  <paper-input-container>
    <iron-input slot="input" auto-validate>
      <input is="iron-input" pattern="\d+">
    </iron-input>
    <paper-input-error slot="add-on">
      <iron-icon icon="icons:error"></iron-icon>
      <span>Only numbers are allowed!</span>
    </paper-input-error>
  </paper-input-container>
<template>

截图: