如何在 Angular 中创建和销毁动态组件

作者 : 慕源网 本文共3674个字,预计阅读时间需要10分钟 发布时间: 2022-03-15 共1.23K人阅读

介绍 

首先,我们需要安装 Angular CLI。安装 Angular CLI 和基本项目设置后,请按照以下步骤操作。 

在这里,我还添加了一个带有基本角度项目创建的组件。 

组件的名称是 dynamicrestory.component.ts

只需按照 app.module.ts 页面中的以下代码 

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { dynamicrestoryComponent } from './dynamicrestory.component';
@NgModule({
  declarations: [
    AppComponent,
    dynamicrestoryComponent
  ],
  entryComponents: [ dynamicrestoryComponent ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

通常使用组件模板中的组件选择器加载组件,该组件模板在 Angular 编译时标识。

组件也可以在运行时使用 ComponentFactory、ComponentFactoryResolver 和 ViewContainerRef 动态加载。

那些需要动态加载的组件也应该在 app.module.ts 文件中 @NgModule 装饰器的 entryComponents 元数据中配置。

强烈推荐

海量程序代码,编程资源,无论你是小白还是大神研究借鉴别人优秀的源码产品学习成熟的专业技术强势助力帮你提高技能与技能。在此处获取,给你一个全面升级的机会。只有你更值钱,才能更赚钱

海量源码程序,学习别人的产品设计思维与技术实践

ComponentFactory

ComponentFactory 用于创建组件的实例。

ComponentFactoryResolver

ComponentFactoryResolver 为特定组件解析 ComponentFactory。

// Create a factory for dynamicrestoryComponent.
const new_component_factory = this.resolver.resolveComponentFactory(dynamicrestoryComponent);

ViewContainerRef 

ViewContainerRef 表示我们可以附加一个或多个视图的容器。

ViewContainerRef 和 createComponent 的一些重要方法用于附加基于 TemplateRef 的嵌入式视图。createComponent() 组件并将其宿主视图插入到视图容器中指定索引处。在我们的动态组件加载器中,它将使用 ViewContainerRef 的 createComponent() 加载组件。 

// Create a component using the factory.
this.componentRef = this.alertContainer.createComponent(new_component_factory);

新建组件的 ComponentRef 并调用 ViewContainerRef 的 clear() 方法会破坏容器中现有的视图。 

// Clear the container alertContainer: ViewContainerRef;
this.alertContainer.clear();

接下来在app.component,ts页面复制代码在下面

import {
    Component,
    ViewChild,
    ViewContainerRef,
    ComponentFactoryResolver,
    ComponentRef
} from '@angular/core';
import {
    dynamicrestoryComponent
} from './dynamicrestory.component';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    @ViewChild('messageContainer', {
        read: ViewContainerRef
    })
    alertContainer!: ViewContainerRef;
    componentRef!: ComponentRef < dynamicrestoryComponent > ;
    constructor(private resolver: ComponentFactoryResolver) {}
    createComponent(componentname: string) {
        // Clear the container.
        this.alertContainer.clear();
        // Create a factory for MessageComponent.
        const factory = this.resolver.resolveComponentFactory(dynamicrestoryComponent);
        // Create a component using the factory.
        this.componentRef = this.alertContainer.createComponent(factory);
        // Pass the value for @Input properties using a component reference instance method.
        this.componentRef.instance.dynamicrestory_msg = componentname + " " + "component";
        alert(componentname + " " + "component" + " " + "created successfully");
    }
    destroyComponent() {
        // destroy a component using the componentRef.
        this.componentRef.destroy();
        alert("component" + " " + "destroy successfully");
    }
}

添加销毁组件。当我们需要动态移除需要的组件时,请参考下面的清除函数。

destroyComponent() {
    // destroy a component using the componentRef.
    this.componentRef.destroy();
    alert("component destroy successfully");
}

请遵循下面的 app.component.html 和 dynamicrestoryComponent 文件代码。

<h3 class="title">Test Dynamic Component Create & Destroy</h3>
<button (click)="createComponent('home')">home component</button>
<button (click)="createComponent('account')">account component</button>
<button (click)="destroyComponent()">destroy component</button>
<ng-template #TextContainer></ng-template>

Dynamicrestory.component.ts 

import { Component, Input } from '@angular/core';
@Component({
  selector: 'dynamicrestory',
  template: `<h2>{{dynamicrestory_msg}}</h2>`,
})
export class dynamicrestoryComponent  {
  @Input()
    dynamicrestory_msg!: string;
}

添加上述代码后,请运行并单击检查动态组件创建。在这里我已经运行并添加了步骤,请按照下面的图片进行操作。

运行应用程序后,我将单击主组件,主组件将在单击参数时创建主字符串传递。

接下来,在 home 组件将清除并创建帐户组件时创建一个帐户组件。

需要手动删除组件只需单击销毁按钮并删除所有动态组件。

最后,我们能够在应用程序中创建和销毁动态组件。我希望这篇文章对我们最有帮助。

 


慕源网 » 如何在 Angular 中创建和销毁动态组件

常见问题FAQ

程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!

发表评论

开通VIP 享更多特权,建议使用QQ登录