简体   繁体   中英

Why does the polymer property binding need a tag in my template?

I am trying to understand how Polymer renders properties in the template of a custom element. I'm seeing some behavior that I can't explain, where some properties are being rendered in one case (when surrounded by tags), but not in another (when tags are not present in the template). To demonstrate the behavior I wrote this Plunker:

http://plnkr.co/WHYZKrjMMTMckw4X6p4Q

Basically what I did is that I wrote the following custom element:

<link rel="import" href="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html">
<dom-module id="characters-label">
  <style>
  </style>
  <template>
    This has {{ncharacters}} characters!
  </template>
</dom-module>
<script>
  Polymer({
    is: "characters-label",
    properties: {
      ncharacters: {
        type: String,
        value: '6'
      }
    }
  });
</script>

and I use it like this in an index.html file:

<!DOCTYPE html>
<html>

  <head>
    <script data-require="polymer@1.0.0" data-semver="1.0.0" src="http://www.polymer-project.org/1.0/samples/components/webcomponentsjs/webcomponents-lite.js"></script>
    <script data-require="polymer@1.0.0" data-semver="1.0.0" src="http://www.polymer-project.org/1.0/samples/components/polymer/polymer.html"></script>
    <link rel="import" href="characters-label.html" />
  </head>

  <body>
    <p>This is before my label</p>
    <div>
      <characters-label></characters-label>
    </div>
    <p>This is after my label</p>
  </body>

</html>

The result doesn't render the value '6' in the HTML, but instead I get the literal contents of the template:

This is before my label
This has {{ncharacters}} characters!
This is after my label

However, if I change my custom element's template to:

<template>
  This has <b>{{ncharacters}}</b> characters!
</template>

Then the result is as expected:

This is before my label
This has 6 characters!
This is after my label

Is this normal behavior?

Yep, that's working as intended. See https://www.polymer-project.org/1.0/docs/devguide/data-binding.html#binding-to-text-content .

To bind to a child element's textContent, you can simply include the annotation inside the child element. The binding annotation must currently span the entire content of the tag:

String concatenation is not supported inside a tag, and the tag can't contain any whitespace:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM