封装< li>的角组件标签 [英] Angular component that encapsulates <li> tag

查看:75
本文介绍了封装< li>的角组件标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些样式列表:

Suppose I have some styled list:

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

现在,我想将每个<li>项目封装到单独的组件中.这样做,我们在最终的DOM中得到了这样的内容:

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>

问题是,它破坏了样式.我们将在项目之间出现错误的边距,错误的边框等.如果使用外部CSS,问题将变得很棘手.

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.

因此,有没有一种方法可以直接将<li>样式应用于<my-item>而无需编辑外部CSS文件?在AngularJS中,指令有一个replace选项,但在Angular中则不存在afaik.

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答案

如@enguerranws所述,为您的组件使用属性选择器,而不是标签选择器

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

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

并像使用它

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

Angular2没有replace选项,并且一段时间以来在Angular 1.x中也已弃用.

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

要允许您<my-li>的用户传递自定义内容,请在模板中添加<ng-content></ng-content>标记(您可以在应为每个<my-li>元素显示的<ng-content>标记之前和之后添加自定义内容.

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>'
  ...)

这篇关于封装&lt; li&gt;的角组件标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆