Angular 7 - 在现有模块中插入新的动态组件
创始人
2024-10-16 16:31:40
0

要在Angular 7中在现有模块中插入新的动态组件,可以按照以下步骤进行操作:

  1. 创建一个新的组件,作为动态组件的模板。例如,创建一个名为DynamicComponent的组件。
import { Component } from '@angular/core';

@Component({
  selector: 'app-dynamic-component',
  template: `
    

Dynamic Component

` }) export class DynamicComponent {}
  1. 在需要插入动态组件的现有模块中声明DynamicComponent。例如,在AppModule中声明。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { DynamicComponent } from './dynamic.component';

@NgModule({
  imports: [BrowserModule],
  declarations: [DynamicComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}
  1. 在需要插入动态组件的现有组件中,使用ViewContainerRefComponentFactoryResolver来动态创建和插入新的组件。
import { Component, ComponentFactoryResolver, ViewContainerRef } from '@angular/core';
import { DynamicComponent } from './dynamic.component';

@Component({
  selector: 'app-existing-component',
  template: `
    

Existing Component

` }) export class ExistingComponent { constructor( private componentFactoryResolver: ComponentFactoryResolver, private viewContainerRef: ViewContainerRef ) {} ngAfterViewInit() { const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicComponent); const componentRef = this.viewContainerRef.createComponent(componentFactory); // 可以通过 componentRef.instance 访问到新创建的动态组件实例 } }

在现有组件的模板中,使用ViewContainerRefcreateComponent()方法来创建动态组件的实例,并将其插入到指定的容器中。可以通过componentRef.instance来访问新创建的动态组件实例。

请注意,要使用ViewContainerRefComponentFactoryResolver,需要在构造函数中注入它们,并将ViewContainerRef与一个带有#dynamicComponentContainer模板引用变量的

元素相关联。

这样,现有组件就会在渲染时动态地将新的动态组件插入到指定的容器中。

相关内容

热门资讯

记者揭秘!德普之星辅助工具如何... 记者揭秘!德普之星辅助工具如何设置,hhpoker德州真的假的,揭秘教程(有挂软件)1、很好的工具软...
盘点一款!pokemmo手机脚... 盘点一款!pokemmo手机脚本辅助器,wepoker有辅助功能吗,解密教程(有挂辅助);建议优先通...
解密关于!wepoker辅助是... 1、解密关于!wepoker辅助是真的吗,wpk辅助器,AI教程(有挂技巧)。2、wepoker辅助...
推荐攻略!we-poker辅助... 推荐攻略!we-poker辅助,hhpoker有后台操作吗,切实教程(有挂辅助)关于hhpoker有...
每日必备!pokemmo手机版... 每日必备!pokemmo手机版透视脚本,wpk辅助器,透明教程(有挂神器);建议优先通过pokemm...
一分钟揭秘!hhpoker是正... 《一分钟揭秘!hhpoker是正规的吗,wepoker怎么挂底牌,玩家教你(有挂透明)》 hhpok...
我来教教大家!wepoker看... 我来教教大家!wepoker看底牌,约局吧德州可以透视吗,揭秘攻略(有挂透视)1、不需要AI权限,帮...
记者揭秘!epoker透视底牌... 记者揭秘!epoker透视底牌,大菠萝辅助器,2025教程(有挂方法);玩家必备必赢加哟《13670...
教程攻略!pokemmo辅助器... 1、教程攻略!pokemmo辅助器手机版下载,智星德州插件2024最新版,玩家教程(有挂技巧)2、进...
玩家交流!hhpoker必备开... 玩家交流!hhpoker必备开挂,wepoker有没有辅助,微扑克教程(有挂攻略);1分钟了解详细教...