Angular 4删除动态添加的组件

时间:2017-06-15 16:19:48

标签: angular

使用这样的东西: https://netbasal.com/dynamically-creating-components-with-angular-a7346f4a982d 我添加了多个组件, 问题是我如何根据点击的组件删除组件?  我要做的就是创建breadCrumbs,当点击面包屑时,将其全部移除。 创建它们我使用这段代码:

createCrumb(name, key, level){
  let data = {name:name, key:key, level,level, diagram: this.diagram};
  const factory = this.this.resolver.resolveComponentFactory(BreadCrumbsButton);
  let componentRef = this.container.createOmponent(factory);
  (<BreadCrumbsButton>componentRef.instance).data = data;
}

这一切都很完美,但我添加了多个。 问题是如何在离开其余部分时删除特定的部分?

3 个答案:

答案 0 :(得分:1)

您可以在其上调用destroy方法:

  createComponent(type) {
    this.container.clear(); 
    const factory: ComponentFactory = this.resolver.resolveComponentFactory(AlertComponent);
    this.componentRef: ComponentRef = this.container.createComponent(factory);

    setTimeout(()=>{
       this.componentRef.destroy(); <--------------------
    }, 2000);
  }

我在这里使用超时进行演示,以便可以在屏幕上看到组件。

答案 1 :(得分:1)

同时使用演示

检查此答案

Dynamically ADDING and REMOVING Components in Angular

更新

现在,您可以使用subject代替interface来获取组件&#39;通信

Read about RxJS Subject

从父项中删除子组件,以便它们之间的通信必须启动但是如何?

在这种情况下使用界面

发生了什么?

父正在创建子节点,当子节点尝试删除它时,它会通过接口告诉其父节点,以便父节点移除它。

import { ComponentRef, ComponentFactoryResolver, ViewContainerRef, ViewChild, Component } from "@angular/core";

// Parent Component
@Component({
    selector: 'parent',
    template: `
    <button type="button" (click)="createComponent()">
        Create Child
    </button>
    <div>
        <ng-template #viewContainerRef></ng-template>
    </div>
  `
})
export class ParentComponent implements myinterface {

    @ViewChild('viewContainerRef', { read: ViewContainerRef }) VCR: ViewContainerRef;

    //manually indexing the child components for better removal
    //although there is by-default indexing but it is being avoid for now
    //so index is a unique property here to identify each component individually.
    index: number = 0;

    // to store references of dynamically created components
    componentsReferences = [];

    constructor(private CFR: ComponentFactoryResolver) {
    }

    createComponent() {

        let componentFactory = this.CFR.resolveComponentFactory(ChildComponent);
        let componentRef: ComponentRef<ChildComponent> = this.VCR.createComponent(componentFactory);
        let currentComponent = componentRef.instance;

        currentComponent.selfRef = currentComponent;
        currentComponent.index = ++this.index;

        // prividing parent Component reference to get access to parent class methods
        currentComponent.compInteraction = this;

        // add reference for newly created component
        this.componentsReferences.push(componentRef);
    }

    remove(index: number) {

        if (this.VCR.length < 1)
            return;

        let componentRef = this.componentsReferences.filter(x => x.instance.index == index)[0];
        let component: ChildComponent = <ChildComponent>componentRef.instance;

        let vcrIndex: number = this.VCR.indexOf(componentRef)

        // removing component from container
        this.VCR.remove(vcrIndex);

        this.componentsReferences = this.componentsReferences.filter(x => x.instance.index !== index);
    }
}


// Child Component
@Component({
    selector: 'child',
    template: `
    <div>
    <h1 (click)="removeMe(index)">I am a Child, click to Remove</h1>
    </div>
    `
})
export class ChildComponent {

    public index: number;
    public selfRef: ChildComponent;

    //interface for Parent-Child interaction
    public compInteraction: myinterface;

    constructor() {
    }

    removeMe(index) {
        this.compInteraction.remove(index)
    }
}

// Interface
export interface myinterface {
    remove(index: number);
}

如果你想测试它,只需创建一个类似comp.ts的文件并将该代码粘贴到该文件中并添加对app.module.ts的引用

@NgModule({
  declarations: [

    ParentComponent,
    ChildComponent

  ],
  imports: [

    //if using routing then add like so
    RouterModule.forRoot([
      { path: '', component: ParentComponent },
      { path: '**', component: NotFoundComponent }
    ]),

  ],
  entryComponents: [

    ChildComponent,  

  ],

答案 2 :(得分:0)

或者,如果您使用ViewContainerRef来保存注入的组件,则可以使用clear()方法。

this.container.clear();

Github source