LandonSchropp
LandonSchropp

Reputation: 10274

Angular 1.5 Component Host Element Attributes

I'd like to be able to set custom attributes on the host element for Angular 1.5 components.

Why?

Here's a simplified example of what I'd like to do (it obviously doesn't work, but I'm looking for something similar):

angular.module("app").component('hello', {

  attributes() {
    return {
      class: "hello " + (this.greeting ? "hello--visibile" : ""),
      data-greeting: this.greeting
    }
  },

  bindings: {
    greeting: "<",
  }
})

It looks like Angular 2.0 supports this feature, but I don't see anything in the docs about supporting it in 1.5. Is there a way to accomplish this for those of us still stuck using .component?

In the past, I would have simply used replace: true to solve this problem, but that's been deprecated and isn't even available for .component.

Upvotes: 5

Views: 2373

Answers (1)

Vadiem Janssens
Vadiem Janssens

Reputation: 4109

As you mention, it is not directly possible as you describe. An attributes property would be usefull, but does not exist as of yet.

A possible work-around would be to use $element inside your controller. This passes a jQuery element as a dependency, so you can add attributes as needed.

angular
    .module('myComponent', [])
    .component('myComponent', {
        bindings: {
                greeting: '<'
        },
        controller: function($element) {
                $element.addClass('hello-world');
                $element.attr('aria-hidden', true);
                $element.data('my-greeting', this.greeting);
        },
        template: 'Define your template here.'
    });

The <myComponent> element would now have a hello-world class and a aria-hidden attribute. It is even possible to use bindings, as described above with greeting.

The angular component definition is just a wrapper around normal directives.

Upvotes: 7

Related Questions