0

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?

I am me
  • 131
  • 2
  • 12
  • There's no such thing as a CSS class. CSS has rulesets, selectors, class selectors, rules, and properties (all of which are sometimes mistakenly called "CSS classes"). HTML has actual classes. – Quentin Apr 06 '17 at 12:31
  • @Quentin : of course, will attempt to update to 'class selector' – I am me Apr 06 '17 at 12:34
  • @Iamme can't you just have a div inside your template (with your class applied) and keep everything of your content inside of it to achieve similar behaviour? – tanmay Apr 06 '17 at 12:38
  • @tanmay : yes, I have that now. But I wanted to avoid that extra nesting tag if possible as it seems superfluous to requirements – I am me Apr 06 '17 at 12:43

1 Answers1

1

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>
Fedaykin
  • 4,482
  • 3
  • 22
  • 32
  • Out of interest, do you happen to know where a verbose API reference is for the $postLink method and $element? I've looked on the Angular site but can only find the $postLink function mentioned within the developer guide. – I am me Apr 06 '17 at 17:10
  • For anyone interested: `$postLink` is referred to as a _lifecycle hook_. Some info on this hook and others can be found via the proceeding link, although I'm yet to find a fully comprehensive explanation (please share if you find anything decent): [Angular 1.5 lifecycle hooks by Todd](https://toddmotto.com/angular-1-5-lifecycle-hooks#postlink) – I am me Apr 06 '17 at 20:03