Assign an arbitrary id on a custom element



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: 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-${}`; 


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


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


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);

export class UuidCustomAttribute {
   static inject = [Element];

    constructor(element){ = uuidv4();


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

Thanks mate!