【发布时间】:2017-10-27 20:51:26
【问题描述】:
为了与现有的执行 DOM 操作的原生 JavaScript 库集成,我希望能够将 Angular 管理的视图附加到 document 中的任何 DOM 元素。
假设 SomeLibrary 在 DOM 中的某处创建了一个容器(我们给它一个可以注入其 HTML 的目标节点):
<body>
<angular-app-root>
<!-- here... -->
<div id="some-library-created-this"></div>
</angular-app-root>
<!-- or more likely, here... -->
<div id="some-library-created-this"></div>
</body>
我引用了div#some-library-created-this DOM 节点。
现在,我有一个可以像这样使用的 Angular 组件:
<angular-component [angularInput]="value">
<!-- what follows isn't the `template`, but what would get set in a ng-content inside of AngularComponent's template -->
<h1>Embedded Content Children</h1>
<hr>
<another-angular-component></another-angular-component>
</angular-component>
这个AngularComponent 现在应该获取其中设置的内容,并将其显示在我们拥有的div#some-library-created-this 节点内。
也就是说,组件的内容不会显示在声明组件的位置,而是显示在任何给定的原生元素中的其他位置。
类似的东西:
<body>
<angular-app-root></angular-app-root>
<div id="some-library-created-this">
<some-kind-of-wrapper> <!-- ? -->
<h1>Embedded Content Children</h1>
<hr>
<another-angular-component></another-angular-component>
</some-kind-of-wrapper>
</div>
</body>
这可能吗?是否有等效的解决方案可以让我从 SomeLibrary 的非托管 DOM 操作逻辑中受益,同时利用 Angular 的功能?
我已经阅读了一些显示相似和高级用例的帖子,例如:
- https://medium.com/front-end-hacking/dynamically-add-components-to-the-dom-with-angular-71b0cb535286
- https://www.lucidchart.com/techblog/2017/04/10/using-angular-2-components-in-a-non-angular-app/(顺便说一句,很有趣)
但那些只谈论创建预先知道的组件,并专门为给定视图创建它们,而不仅仅是把它们扔到屏幕上的其他地方。
【问题讨论】:
-
But those only speak about creating components that are known in advance, and creating them specifically for a given view但在您写Now, I have an Angular component that can be used like this之前,我可以得出结论,您的组件是提前知道的 -
appRef.bootstrap和componentFactory.create有可选参数selectorOrNode可以帮助你 -
我的意思是:AngularComponent 的内容是事先不知道的。我没有将它的
template放在示例中,但是API 使用者会传递什么。基本上是template: '<ng-content></ng-content>'里面的内容。 -
我们不能在根组件中嵌入内容。 JitCompiler 可能会对您有所帮助。但你在这种情况下是不是
标签: angular dom angular2-template dom-manipulation