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

1k Views Asked by At

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>
2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

I found the solution by setting amp-bind on each option.

<amp-state id="selectedColor">
    <script type="application/json">
    {
        "value": "",
        "text": ""
    }
    </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"
    on="tap:AMP.setState({
        selectedColor: {
          text: rouge
        }
      })">rouge</div> <!-- user select this -->
  <div option="blue"
    on="tap:AMP.setState({
        selectedColor: {
          text: bleu
        }
      })">bleu</div>
  <div option="green"
    on="tap:AMP.setState({
        selectedColor: {
          text: vert
        }
      })"
    >vert</div>
</amp-selector>