An angular component that encapsulates the <li> tag

Suppose I have some kind of stylized list:

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

Now I want to encapsulate each <li> element in a separate component. By doing this, we get something like this as a result of the DOM:

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

The problem is that it violates the style. We get the wrong margins between the elements, the wrong borders, etc. And if we use external CSS, the problem becomes unpleasant.

So, is there a way to apply <li> styles directly to <my-item> without editing an external CSS file? AngularJS has a replace option for directives, but it does not exist in Angular.

+9
source share
1 answer

Angular2 answer

As mentioned in @enguerranws, use the attribute selector for your component instead of the tag selector

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

and use it like

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

Angular2 does not have a replace option, and is also deprecated in Angular 1.x after a while.

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

 @Component( selector: '[myLi]', // '[my-li]', template: '<ng-content></ng-content>' ...) 
+10
source

Source: https://habr.com/ru/post/1236697/


All Articles