Search code examples
angularangular-componentscustom-data-attribute

Data-attribute in Angular component


I understand that I can add a data-attribute to an element within my component like this:

<div [attr.data-my]="myDataValue">

But how can I add a data-attribute to the component itself? I would expect to declare it like any other @Input, but I can't find any information about it? Does anyone know?


Solution

  • You can use the following

    @HostBinding('attr.data-my')
    get someValue(): string {
       return this.myDataValue;
    }
    

    You can also add the @HostBinding above an @Input for brevity if it suits your use case - you'll find examples of that too