【问题标题】:Display a managed view outside of the application root in Angular在 Angular 中显示应用程序根目录之外的托管视图
【发布时间】: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 的功能?

我已经阅读了一些显示相似和高级用例的帖子,例如:

但那些只谈论创建预先知道的组件,并专门为给定视图创建它们,而不仅仅是把它们扔到屏幕上的其他地方。

【问题讨论】:

  • 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.bootstrapcomponentFactory.create 有可选参数 selectorOrNode 可以帮助你
  • 我的意思是:AngularComponent 的内容是事先不知道的。我没有将它的template 放在示例中,但是API 使用者会传递什么。基本上是template: '&lt;ng-content&gt;&lt;/ng-content&gt;'里面的内容。
  • 我们不能在根组件中嵌入内容。 JitCompiler 可能会对您有所帮助。但你在这种情况下是不是

标签: angular dom angular2-template dom-manipulation


【解决方案1】:

我设法用&lt;ng-template&gt;s 做到了,这更好,因为组件内部的视图在本机库显示其 DOM 元素之前没有实例化。此外,这让我可以在同一个组件主体内定位本机库的不同 DOM 节点,如下所示:

<angular-component [angularInput]="value">
  <form *angularComponentPartial [formControl]="myForm">
    ...
  </form>

  <ng-container *angularComponentPartial="angularComponentTargets.otherKnownDomNode">
    Send ({{ secondsLeft }} seconds left)
  </ng-container>
</angular-component>

自定义*angularComponentPartial结构指令用于获取用户定义内容的TemplateRef。然后,在ComponentFactoryResolver 的帮助下,它创建了一个特殊的组件并将其安装在库 DOM 节点上。 由于一个简单的模板出口,它将 TemplateRef 传递给唯一作用是显示模板的组件:

<ng-container *ngTemplateOutlet="template"></ng-container>

AngularComponent 甚至不必处理那个伪包含逻辑。仅涉及结构指令和一个微小的模板持有者组件。

如果您对细节的实现感兴趣,那是开源的!我在toverux/ngsweetalert2 中使用它(在撰写本文时,它仍在next 分支中)。它用于在 SweetAlert2 模式中显示动态内容。

【讨论】:

    猜你喜欢
    • 2013-02-10
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 2015-11-15
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    相关资源
    最近更新 更多