angularjsangular-ui-routerangular-componentsangular-component-router

Can a CSS class selector be applied to a component?


I have the following Plunker that uses ui-router and Angular's 1.6x new component feature.

The state 'userRegister' becomes active then initialises the 'userRegister' component. This component injects a new <user-register/> into the <ui-view> then injects the HTML contents of the ng-template script block, which is all working fine.

The final DOM ends up being:

<ui-view class="ng-scope">
    <user-register class="ng-scope ng-isolate-scope">
      <h1 class="header">Create account</h1>
    </user-register>
</ui-view>

However, I cannot find a way to add a CSS class selector to the <user-register/> tag.

e.g. using a class selector called .example I'd like to achieve the following:

<user-register class="example ng-scope ng-isolate-scope">...<user-register/>

Any ideas please?


Solution

  • Sure you could always wrap the template on a div and put the class there.

    If don't want to do it, you can inject the $element and use the $postLink function to add the class you need:

    .component('userRegister', {
        templateUrl: '/views/user-register',
        controller: function($element) {
           this.$postLink = function() {
             $element.addClass('example');
           }
        }
     })
    

    Here is the working plunker:

    https://plnkr.co/edit/VuWu8L9VqrgJRGnxItY2?p=preview

    Final DOM:

    <user-register class="ng-scope ng-isolate-scope example">
      <h1 class="header">Create account</h1>
    </user-register>