有没有办法在Angular中以编程方式呈现组件? [英] Is there a way to programmatically render a component in Angular?

查看:61
本文介绍了有没有办法在Angular中以编程方式呈现组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,有没有一种方法可以通过编程方式将(成一个DOM元素)成角度的组件?

As the title says is there a way to programmatically render (into a DOM element) a component in angular?

例如,在React中,我可以使用 ReactDOM.render 将组件变成DOM元素。我想知道是否可以在Angular中使用类似的东西?

For example, in React I can use ReactDOM.render to turn a component into a DOM element. I am wondering if it's possible to something similar in Angular?

推荐答案

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

At first you'll need to have a template in your HTML file at the position where you'll want to place the dynamically loaded component.

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

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

In the component you can inject the DynamicFactoryResolver inside the constructor. Once you'll execute the loadComponent() function, the DynamicComponent will be visible in the template. DynamicComponent can be whatever component you would like to display.

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 来例如修改公共属性或触发公共属性。该组件实例。

  1. It clears the host
  2. It creates a so called factory object of your component. (resolveComponentFactory)
  3. It creates an instance of your factory object and inserts it in the host reference (createComponent)
  4. You can use the componentRef to, for example, modify public properties or trigger public functions of that components instance.

这篇关于有没有办法在Angular中以编程方式呈现组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆