Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

  • I want to add a class to a component so I can style it. For example, if a component's parent has display: flex set, I'll likely want to set the flex property on the component.
  • It's often useful to conditionally apply a class depending on a component's state.
  • In certain circumstances, I'd like to use ARIA attributes to make a component more accessible.

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.

like image 688
LandonSchropp Avatar asked Jun 17 '16 08:06

LandonSchropp


1 Answers

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.

like image 184
Vadiem Janssens Avatar answered Oct 05 '22 00:10

Vadiem Janssens