【问题标题】:Angular 2. How dynamically created component could call by itself the destroy method?Angular 2. 动态创建的组件如何自己调用destroy方法?
【发布时间】:2017-05-25 18:39:44
【问题描述】:

我被动态组件的破坏所困扰。我会很感激一些提示。 这是我的根组件,它在页面上完美地添加了来自服务的一些组件:

/*Root*/
@Component({
selector: 'convertors',
template: "<div #target></div>"})

export class AppComponent {
@ViewChild('target', {read: ViewContainerRef}) target: ViewContainerRef;

private componentRef: ComponentRef<any>;
constructor(private componentFactoryResolver: ComponentFactoryResolver,
            private viewContainerRef: ViewContainerRef){}

addComponent(){
    let someComponent = this.service.getService("someComponent");
    const factory = this.componentFactoryResolver.resolveComponentFactory(someComponent);
    this.componentRef = this.target.createComponent(factory);
}}

这是我的子组件,它是由根组件添加的。它必须自毁:

@Component({
selector: 'convertors',
template: "<button (click)="deleteComponent()" >Delete</button>"})
export class someComponent{
    deleteComponent(){
    /*How could I implement this function?*/
    }
}

如何实现 deleteComponent() 方法? 谢谢!

【问题讨论】:

  • 好的,我找到了解决方案。如果有人在这个问题上需要帮助,我会回答。

标签: angular2-components


【解决方案1】:

好的,我的解决方案使用消息服务。如果您不知道它的作用,请查看here。这很简单。 首先,我为任何动态组件分配唯一 ID。接下来,我会在地图中保留对组件及其 id 的引用。

  private componentRef: ComponentRef<Component>;

  onComponent(event: string){
    let component = "ref to any component"
    const factory = this.componentFactoryResolver.resolveComponentFactory(component);
    let componentRef = this.target.createComponent(factory);
    let id = "id" + this.index;
    (<any>componentRef.instance).componentId = id;
    this.idMap.set(id, componentRef);
    this.componentRef = componentRef;
    this.index += 1;
  }

其次,点击子视图的事件通过消息服务将其 id 发送给父级。考虑在孩子中声明的“componentId:string”。但它是在父级中分配的!

<a (click)="deleteComponent()"></a>

private componentId: string;

deleteComponent() : void {
    this.messageService.sendMessage(this.componentId);
}

最后,我们的父级从消息服务接收到 id。接下来,它在地图中寻找孩子的参考。最后,我们调用原生方法 this.target.remove("child index in componentRef") 来移除组件。考虑到,componentRef 有他自己的子索引。

this.subscription = this.messageService.getMessage()
    .subscribe(message => this.removeChild(message))

removeChild(message){
    let component = this.idMap.get(message.id);
    let indice = this.target.indexOf(component);
    this.target.remove(indice);
    this.idMap.delete(message.id);
}

如果知道如何改进此解决方案,请写在评论中。我有一种感觉,它可能会更好。谢谢。

【讨论】:

    猜你喜欢
    • 2017-07-07
    • 1970-01-01
    • 2016-11-11
    • 2017-05-19
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 2018-08-28
    相关资源
    最近更新 更多