Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind an amp-state's initial value

Tags:

amp-html

I want to initialise an amp-state as follows:

<amp-state id="tabs">
  <script type="application/json">
  {
    "selected": "latest"
  }
  </script>
</amp-state>

Then have this initialised value shown on first page request:

<p [text]="tabs.selected"><p>

This doesn't work. The contents of the p tag are only updated when there is a state change. Eg from a button:

<button on="tap:AMP.setState({tabs: {selected: 'top'}})">Press me</button>

I would like elements on the page to reflect the initialised state before further user interaction.

Codepen: https://codepen.io/powlo/pen/VMpVRm/?editors=1000

like image 408
powlo Avatar asked Sep 27 '17 13:09

powlo


People also ask

Why does AMP-bind issue a warning when a state variable changes?

In development mode, amp-bind will issue a warning when the default value of a bound attribute doesn't match its corresponding expression's initial result. This can help prevent unintended mutations caused by changes in other state variables. For example: <!--

How do I reference state variables in the <AMP-state> component?

The <amp-state> component contains different states and their state variables. While this defines a state, it will not reflect on the page until after a user interacts. Use expressions to reference state variables. If the JSON data is not nested in the <amp-state> component, reference the states via dot syntax.

What is the difference between AMP pushState() and AMP bind()?

Using AMP.pushState () sets the current state to the most recent pushed state. amp-bind uses JavaScript-like expressions that can reference the state. Expressions may only access the containing document's state. Expressions do not have access to window or document. global references the top-level state.

What is the size of AMP state data?

Each AMP document that uses amp-bind has document-scope mutable JSON data, or state. An <amp-state> element's JSON data has a maximum size of 100KB. Expressions are not evaluated on page load, but you may define an initial state. The <amp-state> component contains different states and their state variables.


1 Answers

amp-bind expressions are not evaluated on page load. This is intentional to avoid layout jumps on page load. If you want to dynamically initialize elements on page load, you need to use the amp-list extension (even if it is only a single element).

like image 186
Sebastian Benz Avatar answered Oct 09 '22 10:10

Sebastian Benz