How to reference element in slot of CustomElement

I want to create a custom element for a password input that has an “eye” icon that allows the user to show/hide the password. I did the following:

password.html

<template bindable="password">
   <require from="resources/elements/password.css"></require>
   <input class="password" type="${showPass ? 'text' : 'password'}" value.bind="password" />
   <i class="fas ${showPass ? 'fa-eye-slash' : 'fa-eye'}" click.delegate="showPass = !showPass"></i>
<template>

This works great, but I began to realize that going about it this way keeps me from accessing the attributes of the input – placeholder, disabled, etc.

I could add bindable values for each attribute of the input element that I wanted to bind to – but that seems a bit of a pain.

I thought about using content projection using a slot so I could add the <input> element myself like so:

<password >
    <input type="password"  />
</password>

However, now my CustomElement has no way of changing the type of the <input> element. I can do the following:

<password showpass.two-way="myshowvar">
     <input type="password" type="${myshowvar ? 'text' : 'password'}" />
</password>

But I want that logic embeded in the Custom Element.

Is there a way to pass a reference to my input into the Custom Element? Something along the lines of this?

<template bindable="elementref">
    <slot></slot>
    <i class="fas ${showPass ? 'fa-eye-slash' : 'fa-eye'}" 
      click.delegate="showPass = !showPass; elementref.type = showPass ? 'text' : 'password';"></i>
</template>

Thanks for your help!

1 Like

I found this SO answer which seems relevant. Unfortunately, when I attempted to recreate it in a fork of the Aurelia CodeSandbox, I was unsuccessful. I’m unsure why and have currently run out of time to try, but maybe these links will help you.

2 Likes

Thanks so much! That did the trick. Like you, I couldn’t get it to work in Aurelia CodeSandbox – doesn’t seem to like the <require></require> tag in html. However, I did add it to my code and got it to work!

Thanks again!

2 Likes

Yea the require tag doesn’t work properly in the sandbox. @bigopon has sandboxes where you can use elements with the require tag. I believe he is utilizing au-script?

1 Like

I think i havent seen issues filed. Which sandboz that it doesnt work propely?

I haven’t investigated much, but the typescript forks don’t seem to work.

1 Like

@bigopon, here’s the example I was trying to create for @roddharris.
https://codesandbox.io/s/aurelia-typescript-sandbox-2nbim

You’ll note that the child element is always undefined when output to the console.

I forked from https://codesandbox.io/s/zw9zjy0683

1 Like