如何实现 Angular 2 内容包装器指令(如 jQuery 的 wrapInner)

How to Implement an Angular 2 content wrapper Directive (like jQuery's wrapInner)

我想实现一个 Angular 2 指令,它的行为类似于 jQuery's wrapInner method
我正在编写的库将仅使用 angular 2+(没有 jQuery)。

基本上,该指令将采用它所应用的元素或组件的内容,并将该内容包装在 div 中(或者可能将其包装在其他 html 标记中作为参数传入)

例如,

<myComponent wrapInner>
   ... All The Content ...
</myComponent>  

应该会产生类似的结果,

<myComponent >
   <div class="innerStyles" >
      ... All The Content ...
   </div>
</myComponent>  

我不确定最 angular 风格的 'idiomatic' 方法是什么,因为它似乎涉及操纵 DOM,即 discouraged

那么,这可能是结构指令更好的东西吗?或者涉及以某种方式操纵 templates or using ViewContainer?我不知道如何使用这些。

但是,我整理了一个 plunker,我使用 (discouraged) 不安全且低效的方式来解决这个问题;通过操纵 DOM 到 ElementRef

https://plnkr.co/edit/PyVyzv3KUQ8IcsdNnVt0

请提供帮助。
非常感谢!

我不认为没有直接 DOM 操作的方法。

要完成这项工作,您需要一个组件并像这样使用它

<myComponent wrapInner>
  <wrap-inner>
   ... All The Content ...
  </wrapInnter>
</myComponent>  

但是没有办法去掉包装部分周围的<wrap-inner>(<div class="innerStyles" >)

目前不可能。 但是 Angular 团队在 backlog 上有这个功能。

您可以在 https://github.com/angular/angular/issues/8785

关注进度