栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

动态添加和删除角度组件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

动态添加和删除角度组件

您可以尝试实现以下目标:通过使用动态创建组件

ComponentFactoryResolver
,然后将其注入
ViewContainerRef
。动态执行此操作的一种方法是将组件的类作为将创建和注入组件的函数的参数传递。

请参见下面的示例:

import {  Component,  ComponentFactoryResolver, Type,  ViewChild,  ViewContainerRef} from '@angular/core';// Example component (can be any component e.g. app-header app-section)import { DraggableComponent } from './components/draggable/draggable.component';@Component({  selector: 'app-root',  template: `    <!-- Pass the component class as an argument to add and remove based on the component class -->    <button (click)="addComponent(draggableComponentClass)">Add</button>    <button (click)="removeComponent(draggableComponentClass)">Remove</button>    <div>      <!-- Use ng-template to ensure that the generated components end up in the right place -->      <ng-template #container>      </ng-template>    </div>  `})export class AppComponent {  @ViewChild('container', {read: ViewContainerRef}) container: ViewContainerRef;  // Keep track of list of generated components for removal purposes  components = [];  // Expose class so that it can be used in the template  draggableComponentClass = DraggableComponent;  constructor(private componentFactoryResolver: ComponentFactoryResolver) {  }  addComponent(componentClass: Type<any>) {    // Create component dynamically inside the ng-template    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentClass);    const component = this.container.createComponent(componentFactory);    // Push the component so that we can keep track of which components are created    this.components.push(component);  }  removeComponent(componentClass: Type<any>) {    // Find the component    const component = this.components.find((component) => component.instance instanceof componentClass);    const componentIndex = this.components.indexOf(component);    if (componentIndex !== -1) {      // Remove component from both view and array      this.container.remove(this.container.indexOf(component));      this.components.splice(componentIndex, 1);    }  }}

笔记:

  1. 如果您希望以后更轻松地删除这些组件,可以在局部变量中跟踪它们,请参见

    this.components
    。或者,您可以遍历内的所有元素
    ViewContainerRef

  2. 您必须将组件注册为输入组件。在模块定义中,将组件注册为entryComponent(

    entryComponents: [DraggableComponent]
    )。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/575458.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号