【问题标题】:Is there a way to programmatically render a component in Angular?有没有办法以编程方式在 Angular 中渲染组件?
【发布时间】:2020-06-15 01:56:35
【问题描述】:

正如标题所说,有没有办法以编程方式将组件渲染(到 DOM 元素中)角度?

例如,在 React 中,我可以使用 ReactDOM.render 将组件转换为 DOM 元素。我想知道是否有可能在 Angular 中进行类似的操作?

【问题讨论】:

标签: javascript angular dom element


【解决方案1】:

首先,您需要在 HTML 文件中放置动态加载组件的位置有一个模板。

<ng-template #placeholder></ng-template>

在组件中,您可以在构造函数中注入DynamicFactoryResolver。执行loadComponent() 函数后,DynamicComponent 将在模板中可见。 DynamicComponent 可以是您想要显示的任何组件。

import { Component, VERSION, ComponentFactoryResolver, ViewChild, ElementRef, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent  {
  @ViewChild('placeholder', {read: ViewContainerRef})
  private viewRef: ViewContainerRef;

  constructor(private cfr: ComponentFactoryResolver) {}

  loadComponent() {
    this.viewRef.clear();
    const componentFactory = this.cfr.resolveComponentFactory(DynamicComponent);
    const componentRef = this.viewRef.createComponent(componentFactory);
  }
}

这是Stackblitz

loadComponent 函数的作用是:

  1. 清除主机
  2. 它会为您的组件创建一个所谓的工厂对象。 (resolveComponentFactory)
  3. 它会创建一个工厂对象的实例并将其插入宿主引用 (createComponent)
  4. 您可以使用componentRef 来修改公共属性或触发该组件实例的公共功能。

【讨论】:

    【解决方案2】:

    如果要将angular组件渲染成非angular编译的Dom元素,那么我们就无法获取ViewContainerRef。然后您可以使用 Angular cdk 门户和门户主机概念来实现这一点。 使用任何 DOMElememt、injector、applicationRef、componentFactoryResolver 创建门户主机。 使用组件类创建门户。 并将门户附加到主机。 https://medium.com/angular-in-depth/angular-cdk-portals-b02f66dd020c

    【讨论】:

    • 如果您可以添加演示如何执行此操作的代码而不是仅仅描述它,这将改善您的答案。
    • 我的公司政策规定不添加代码。我添加了我阅读这篇文章的中篇文章的链接
    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 2023-03-29
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多