Steph Locke
Steph Locke

Reputation: 6166

Multiple amp-selectors with state setting events

I have two amp-selector elements on a page:

<amp-selector layout="container" on="select: AMP.setState({
      a1SelectedOption: event.targetOption
    })">
  <div option="a" selected>Option A</div>
  <div option="b">Option B</div>
</amp-selector>
<amp-selector layout="container" on="select: AMP.setState({
      a2SelectedOption: event.targetOption
    })">
  <div option="c" selected>Option C</div>
  <div option="d">Option D</div>
</amp-selector>

I then have text placeholders:

<h3 id="a1" [text]="a1SelectedOption">a</h3>
<h3 id="a2" [text]="a2SelectedOption">c</h3>

When someone first interacts with either selector the other placeholder gets triggered and updates the text to null e.g. after page load, select Option B, placeholders html becomes <h3 id="a1" [text]="a1SelectedOption">b</h3> <h3 id="a2" [text]="a2SelectedOption">null</h3>.

I suspect this is because both use event.targetOption in the on statement for each selector but the docs on events aren't clear for me as to how to resolve.

What is the appropriate way to set variable values that is independent of other amp-selectors?

Upvotes: 1

Views: 202

Answers (1)

Steph Locke
Steph Locke

Reputation: 6166

AMP event model seems to trigger all the state values to assess so it flashes the other variable into creation with a null value.

To prevent this variables must be initialised with a default i.e.

<amp-state id="a1SelectedOption"><script type="application/json"> "a" </script></amp-state>
<amp-state id="a2SelectedOption"><script type="application/json"> "c" </script></amp-state>

Upvotes: 1

Related Questions