Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular component that encapsulates <li> tag

Tags:

css

angular

Suppose I have some styled list:

<ul>
  <li>...</li>
  <li>...</li>
  ...
</ul>

Now I want to encapsulate each <li> item into separate component. Doing that, we get something like this in a resulting DOM:

<ul>
  <my-item><li>...</li></my-item>
  <my-item><li>...</li></my-item>
  ...
</ul>

The problem is, it breaks styling. We will get wrong margins between items, wrong borders etc. And if we use external CSS, the problem becomes nasty.

So, is there a way to apply <li> styles directly to <my-item> without editing external CSS file? In AngularJS there is a replace option for directives, but in Angular it doesn't exist afaik.

like image 851
troorl Avatar asked Nov 24 '15 11:11

troorl


1 Answers

Angular2 answer

As @enguerranws mentioned use an attribute selector for your component instead of a tag selector

@Component(selector: '[myLi]', ...
//@Component(selector: '[my-li]', ...

and use it like

<li myLi>...
<!-- <li my-li>... -->

Angular2 doesn't have the replace option and it's also deprecated in Angular 1.x since a while.

To allow users of your <my-li> to pass custom content add a <ng-content></ng-content> tag to the template (you can add custom content before and after the <ng-content> tag that should appear for each <my-li> element.

@Component(
  selector: '[myLi]', // '[my-li]', 
  template: '<ng-content></ng-content>'
  ...)
like image 121
Günter Zöchbauer Avatar answered Oct 16 '22 22:10

Günter Zöchbauer