Switch/case statements in templates

I have been experimenting with switch/case statements in templates.
I tried to replace:

<template repeat.for="item of model.items">
 <item if.bind="item.type ==='itm'" model.bind="item"></item>
 <header if.bind="item.type ==='hdr'" model.bind="item"></header>
</template>

with

<template repeat.for="item of model.items" switch.bind="item.type" >
 <item case='itm' model.bind="item"></item>
 <header case='hdr' model.bind="item"></header>
</template>

I noticed that in second case, even though element was not rendered in DOM, it’s view model was instantiated (it’s constructor has been hit), and it’s model was bound to undefined. (alpha 26).
Is this a bug or expected behavior?

1 Like

just as an idea, try wrapping your elements with a div and place the switch onto it.

and no it definitely shouldnt be that way. @Sayan751 perhaps really an overseen issue?

1 Like

Tried it. It behaves the same.

It seems to be working. Check this minimal example: Typescript (forked) - StackBlitz

did you check for the vm not getting created? i’m not on PC so cant do it myself, but my understanding was it wirked for @zeko77 but he got an unexpected sideeffect

Sorry I misread.

even though element was not rendered in DOM, it’s view model was instantiated (it’s constructor has been hit)

Yes, that’s supposed to happen. The components (or better said, controllers) get created, but those are not attached to DOM unless activated. In Au2 you can keep the instantiated VMs around and de/activate those on-demand.

it’s model was bound to undefined

That’s because it is not bound yet :slight_smile:

oh ok, the same with if bindings?

The thing is that I am subscribing to event aggregator events in conditionally rendered components.

In first (if) case, as expected, elements are not created at all and no events fire on their vm.

In second (switch) case, view-model of not rendered component was created, and events were firing there too.

Since I was handling the bound item within event handlers, I got an error for trying to operate on undefined bound model.

I have forked the example and reproduced this:

Thank you for reporting this issue. From primary glance, it seems an incorrect behaviour. I am in the process of finding a solution.

1 Like

Meanwhile, you can use this workaround: Au2-switch-repeat-example-for-discourse (forked) - StackBlitz

Thank you. This is a really cool feature, and you guys are doing an excellent job.

3 Likes

The instantiation behaviour is now changed, and the changes should be out with the next release. With the ‘dev’-build of the packages the changes are already available though.

4 Likes