有没有办法以编程方式在 Angular 中呈现组件?
Is there a way to programmatically render a component in Angular?
正如标题所说,有没有办法以编程方式呈现(到 DOM 元素中)angular 中的组件?
例如,在 React 中我可以使用 ReactDOM.render
将组件变成 DOM 元素。我想知道是否可以在 Angular?
中做类似的事情
首先,您需要在 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
函数的作用是:
- 清除主机
- 它为您的组件创建一个所谓的工厂对象。 (
resolveComponentFactory
)
- 它创建您的工厂对象的实例并将其插入主机引用 (
createComponent
)
- 您可以使用
componentRef
来修改 public 属性或触发该组件实例的 public 功能。
如果要将angular组件渲染成angular未编译的Dom元素,则无法获取ViewContainerRef。然后你可以使用 Angular cdk portal 和 portal host 概念来实现这个。
使用任何 DOMElememt、注入器、applicationRef、componentFactoryResolver 创建门户主机。
使用组件 class 创建门户。
并将门户附加到主机。
https://medium.com/angular-in-depth/angular-cdk-portals-b02f66dd020c
正如标题所说,有没有办法以编程方式呈现(到 DOM 元素中)angular 中的组件?
例如,在 React 中我可以使用 ReactDOM.render
将组件变成 DOM 元素。我想知道是否可以在 Angular?
首先,您需要在 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
函数的作用是:
- 清除主机
- 它为您的组件创建一个所谓的工厂对象。 (
resolveComponentFactory
) - 它创建您的工厂对象的实例并将其插入主机引用 (
createComponent
) - 您可以使用
componentRef
来修改 public 属性或触发该组件实例的 public 功能。
如果要将angular组件渲染成angular未编译的Dom元素,则无法获取ViewContainerRef。然后你可以使用 Angular cdk portal 和 portal host 概念来实现这个。 使用任何 DOMElememt、注入器、applicationRef、componentFactoryResolver 创建门户主机。 使用组件 class 创建门户。 并将门户附加到主机。 https://medium.com/angular-in-depth/angular-cdk-portals-b02f66dd020c