amp-htmlamp-bind

How to set text content of amp-selector into amp-state


I would like to know how can I get the text content based on the option which a user selected and set it to amp-state. For example, if a user selects "red" option. I want to set the "rouge" into amp-state not "red". I know that I can get value by event.targetOption inside setState function. However, could not find how to get and set text into amp-state.

<amp-state id="selectedColor">
    <script type="application/json">
    {
        "value": ""
    }
    </script>
</amp-state>

<p>Selected Color <span [text]="selectedColor.value"></span></p>

<amp-selector
  layout="container"
  on="select:AMP.setState({
        selectedColor: {
          value: event.targetOption
        }
      })">
  <div option="red">rouge</div> <!-- user select this -->
  <div option="blue">bleu</div>
  <div option="green">vert</div>
</amp-selector>

My expected output is as below

<p>Selected Color <span>rouge</span></p>

not

<p>Selected Color <span>red</span></p>

Solution

  • You can do it like this:

    <!-- 1. Initialize colorMap -->
    <amp-state id="colorMap">
      <script type="application/json">
        {
          "red": "rouge",
          "blue": "bleu",
          "green": "vert"
        }
      </script>
    </amp-state>
    
    <!-- 2. On select: set new state of selectedColor -->
    <amp-selector
      layout="container"
      on="select:AMP.setState({selectedColor: event.targetOption})">
      <div option="red">rouge</div>
      <div option="blue">bleu</div>
      <div option="green">vert</div>
    </amp-selector>
    
    <!-- 3. Bind the selectedColor value as identifier for the colorMap -->
    <p>Selected Color <span [text]="colorMap[selectedColor]"></span></p>
    
    1. Initialize colorMap as predefined <amp-state>
    2. On select: set new state of the selectedColor as a single string (not an object with key: value)
    3. Bind the selectedColor value as identifier for the colorMap

    Note that the values ​​of the color map and the selector must be identical. I would prefer to use a template engine.