Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Binding elements in conditional block

$
0
0

The conventional way to reference an HTML element is Svelte is to introduce a variable and bind:this the element to the variable. Like this

<script>  let divName;</script><div bind:this={divName}></div>

In this way we can use the variable divName to reference that element and use it call functions or applying styles.

I'm facing problems when trying to do the same with an element inside a conditional block. In particular when referencing an element which is just became visible. For example

<script>function enable(){  someCondition = true;  if (someCondition) divName.innerText = 'hello';}</script>{#if someCondition}<div bind:this={divName}></div>{/if}

Even if the condition is satisfied, when trying to access the element I get the error divName is null.

A workaround is to wait a few milliseconds between making the element visible and actually referencing it. I made a full working example on repl. In a real application, this doesn't always works, plus it's not extremely nice.

I was wondering if anyone know the reason for this and what is the correct way to handle these situations. Thank you very much.


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>