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.
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>'
...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With