Is there a way to add a class to the component root element?
Asked Answered
I

1

9

Except for adding the class in html.

I mean something like that:
In html

<my-component></my-component>

In js

angular.module('app').component('myComponent', {
  template: '<div class="inner-element">Inner element</div>',
  className: 'outer-element' <--- wanted property
});

This is how I want it to look after render:

<my-component class="outer-element"> <--- that's what I want to get
  <div class="inner-element">Inner element</div>
</my-component>
Illation answered 5/7, 2017 at 12:28 Comment(3)
What exactly do you want to do?Immovable
@RafaelGadottiBachovas, I want to add a class to the root element.Illation
I don't know how can I describe this more extended.Illation
A
9

You could specify controller that adds class on component init

controller: function($element) {
  this.$onInit = function() {
    $element.addClass('outer-element')
  };
}

But this kinda goes against encapsulation and such.

Acceptation answered 5/7, 2017 at 13:48 Comment(4)
Thanks! But if there isn't special property so how should I do this in more 'encapsulation and such' way? I need the class to organize my CSS.Illation
@Illation Ideally parent template should add classes to elements (components) it renders depending on its own data and state. Can't you simply use tag name (my-component {background-color: navy;}) to organize your CSS?Acceptation
I can but I'd prefer to use classname in CSS. But anyway thanks to you! I accept your answer.Illation
How can you achieve flexible-component-layout without "breaking encapsulation"? (Imagine to have a Timeline component with multiple Event child-components with the need of being flex-100 or flex-50 based on device width)Navigate

© 2022 - 2024 — McMap. All rights reserved.