1

Hi I have created a custom element named as 'panel' and a custom attribute 'panel-type'. I want to restrict this 'panel-type' can be used only in 'panel' element. Is there any way to do that?

<panel value.bind='panel' panel-type='default'></panel>

--should work. But no other element can use 'panel-type'. like-

<some-other-tag panel-type='default'></some-other-tag>

--shouldn't work

Tuhin
  • 3,335
  • 2
  • 16
  • 27
  • What is your custom attribute doing? Can we see the code? – Tom Jun 01 '17 at 08:03
  • @thebluefox custom element is doing nothing specific. I just started learning aurelia. Its for my own knowledge – Tuhin Jun 01 '17 at 08:22
  • sounds like it's a over-kill to use custom attribute. `@bindable panelType` inside your panel component is enough for your use case. BYI, you can pass a pure string to a bindable just like what you did there. – huocp Jun 05 '17 at 05:12

1 Answers1

1

Without seeing the code of your Custom Attribute - I can't tailor this to your specific needs - but it's easily possible;

In your Custom Attribute you have access to the the Element property - which is the physical element you've attached the attribute to. Therefore, you can simply use native JavaScript to get the elements tag name;

import {inject, LogManager} from "aurelia-framework";

@inject(Element)
export class panelTypeCustomAttribute {

    allowedElememt = false;

    constructor(Element) {
        this.element = Element;

        if(this.element.tagName == "PANEL") {
            this.allowedElement = true;
        } else {
            LogManager.getLogger('testCustomAttribute').warn("The panel-type custom attribute can only be used on <panel /> elements");
        }
    }

    foo() {
        // Then you can check for the allowedElement flag in any of your methods;
        if(this.allowedElement) {
            // Do your thing
        }
    }
 }
Tom
  • 4,257
  • 6
  • 33
  • 49
  • Thanks for the solution. But I am looking for a one line code. There could be some annotation. – Tuhin Jun 01 '17 at 08:21
  • "there could be some annotation"? – Tom Jun 01 '17 at 08:21
  • annotation like @restrict 'element-name' kind of. It could be great – Tuhin Jun 01 '17 at 08:23
  • Oh, you mean a decorator. To my knowledge - there isn't a decorator that does what you require. You can see the template decorators here; https://github.com/aurelia/templating/blob/master/src/decorators.js – Tom Jun 01 '17 at 08:27