Assign an arbitrary id on a custom element

Hi,

I’d like to be able to set an arbitrary id while declaring custom elements in the markup. This will enable some advanced component scenarios such as dependant drop down lists.

I’ve seen mostly this technique: https://github.com/aurelia-ui-toolkits/aurelia-materialize-bridge/blob/master/src/dropdown/dropdown.js wich it ends up creating a sequential element counter for each component in the DOM.

Is there a way to declare the element id as I normally would do with a standard html element?

Does calling a function from the markup solve your scenario?

i.e. HTML

<div id="${getId()}" ...

and TS

getId() {
    return "arbitrary-id";
}

You could pass an argument and use it too e.g. getId('mypre-') and protected getId(prefix) { ...

You can also access other ViewModel variables within the interpolated string e.g. getId(myvar)

I don’t think I can do that, because I’m having a custom element which I’m using around. So I’d like to assign an id to that element in the HTML template.

You could place a bindable attribute in your component and then assign it inside your view template.

import { bindable } from 'aurelia-framework';

export class MyComponent {
    // default random ID (you could make this a two-way binding if you'd like to either assign it manually or get the random default set value)
    @bindable theId = `id-${Date.now()}`; 
}

template

<template>
    <div id.bind="theId"></div>
</template>

view

<my-component the-id="myNewId"></my-component>
1 Like

You could implement it as a custom attribute. Here’s an example

<div uuid repeat.for="i of 10"></div>
import {customAttribute} from 'aurelia-framework';

function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

@customAttribute('uuid')
export class UuidCustomAttribute {
   static inject = [Element];

    constructor(element){
      element.id = uuidv4();
    }  
}

https://gist.run/?id=b537e43283992ce5438a4e6e72bb9129

3 Likes

Yes, this is what I was trying todo and it works.

Thanks mate!