【问题标题】:is there way to create component those HTML template replaces custom selector?有没有办法创建那些 HTML 模板替换自定义选择器的组件?
【发布时间】:2016-04-01 12:27:27
【问题描述】:

我正在尝试自学 angular2。我试图构建组件“触发调整大小”,我想将其呈现为:

<a class="hidden-xs" href="">
    <em class="fa fa-navicon"></em>
</a>

而不是:

<trigger-resize>

   <a class="hidden-xs" href="">
      <em class="fa fa-navicon"></em>
   </a>
</trigger-resize>

(我不想渲染自定义选择器)

在 angular 1 中。我知道它可以通过“replace:true”选项来实现,但是是否可以在 angular2 中实现它?

亲切的问候

【问题讨论】:

  • 如何使用&lt;a&gt; 上的属性作为选择器而不是&lt;a trigger-resize class="hidden-xs"... &gt; 之类的标记,然后在组件注释中使用[trigger-resize] 作为选择器?
  • 我不想让所有的“a”标签都变成“trigger-resize”,这可能吗?
  • 我解释它的方式首先是带有trigger-resize 属性的标签变成trigger-resize,但也许你还是想使用指令。如果您想添加可调整大小的行为,则组件不是正确的方法。
  • 非常感谢,它正在工作!!!

标签: angular angular2-directives


【解决方案1】:

一种方法是使用属性

<a triggerResize class="hidden-xs" href=""></a>

其中有一个类似的组件

@Component({
    selector : 'a[triggerResize]', //select all <a> tags with triggerResize attribute
    template : '<em class="fa fa-navicon"></em>'
})

CamelCase 属性现在是 angular2 中自定义属性的正确语法

【讨论】:

    【解决方案2】:

    这个问题的直接答案是“否”——您的自定义元素/选择器将位于 HTML 中。引用Angular 1 to Angular 2 Upgrade Strategy doc

    Angular 2 不支持替换其宿主元素的指令(在 Angular 1 中替换为 true 指令)。在许多情况下,这些指令可以升级为常规组件指令。

    也就是说,对于您的特定用例,正如其他人已经提到的那样,使用属性选择器的组件可以工作。

    另见

    【讨论】:

      【解决方案3】:

      您可以使用&lt;a&gt; 上的属性作为选择器,而不是像&lt;a trigger-resize class="hidden-xs"... &gt; 这样的标签,然后在组件注释中使用[trigger-resize] 作为选择器。

      <a trigger-resize class="hidden-xs" href="">
          <em class="fa fa-navicon"></em>
      </a>
      
      @Component({
          selector : '[triggerResize]'
          template : '<em class="fa fa-navicon"></em>'
      })
      

      这对于需要特定标签名称的其他情况也非常有用,例如 &lt;li&gt;&lt;ul&gt;&lt;tr&gt; 内 `

      <ul>
        <li myLi></li>
      </ul>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 2021-12-22
        • 2018-01-11
        • 2021-09-27
        • 1970-01-01
        • 1970-01-01
        • 2011-10-28
        相关资源
        最近更新 更多