0
votes

I would like to implement an Angular 2 directive that behaves like jQuery's wrapInner method.
The library I'm writing will use angular 2+ only (no jQuery).

Basically, the directive will take the content of the element or component it has been applied to, and wrap that content in a div (or perhaps wrap it in some other html tag that's passed in as a parameter)

For example,

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

should result in something like,

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

I am not sure what the most angular-style 'idiomatic' approach to this, as it seems to involves manipulating the DOM which is discouraged.

So could this perhaps be something that is better off being a Structural directive? Or involve manipulating templates or using ViewContainer in some way? I dont know how to use those.

However, I have put together a plunker where I use the (discouraged) insecure and inefficient way of going about this; by manipulating DOM through ElementRef.

https://plnkr.co/edit/PyVyzv3KUQ8IcsdNnVt0

Kindly Assist.
I really appreciate it!

2
Just ignore that ElementRef is insecure. It's not more insecure that using jQuery. " do not automatically protect you from security vulnerabilities" means that you are not automatically secured by Angular. If you take care that you are not doing things that cause security issues yourself, it's perfectly secure. - Günter Zöchbauer
It's not just security that's a problem... in my plunker I found I had to manually loop through and add every child, grand child, great-grand-child .. node of every kind.. if their several layers of nested nodes this will become efficiency nightmare I imagine - Somo S.
There is nothing Angular2 provides. You can search if there are some JS approaches that make it easier. - Günter Zöchbauer

2 Answers

0
votes

I don't think there is a way to do it without direct DOM manipulation.

To make this work you would need a component and use it like

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

but there is no way to get rid of <wrap-inner> around the wrapper part (<div class="innerStyles" >)

0
votes

Not possible at the moment. But the Angular team has this feature on backlog.

You can follow progress at https://github.com/angular/angular/issues/8785