is there way to create component those HTML template replaces custom selector?

此生再无相见时 提交于 2019-12-17 20:55:01

问题


i'm trying to teach myself angular2. I trying to build component "trigger-resize", which i want to render as :

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

and NOT as:

<trigger-resize>

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

(i dont want custom selector to render)

In angular 1. i know it would be achieved by "replace:true" option, but is it possible to achieve it in angular2?

Kind Regards


回答1:


One way to do it is to use an attribute

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

Which has a component like

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

CamelCase attributes are the proper syntax now for custom attributes in angular2




回答2:


The direct answer to the question is "no" – your custom element/selector will be in the HTML. To quote the Angular 1 to Angular 2 Upgrade Strategy doc:

Directives that replace their host element (replace: true directives in Angular 1) are not supported in Angular 2. In many cases these directives can be upgraded over to regular component directives.

That said, for your specific use case, as others have already mentioned, a component that uses an attribute selector would work.

See also

  • Remove the host HTML element selectors created by angular component
  • Angular2 table rows as component



回答3:


You can use an attribute on <a> as selector instead of a tag like <a trigger-resize class="hidden-xs"... > and then in the component annotation use [trigger-resize] as selector.

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

This is also quite useable for other situations where specific tag names are required like <li> inside <ul> or <tr> inside `

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



来源:https://stackoverflow.com/questions/34480243/is-there-way-to-create-component-those-html-template-replaces-custom-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!