我被动态组件的破坏所困扰。如果有一些提示,我将非常感激。 这是我的根组件,它在页面上完美地添加了服务中的一些组件:
/*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);
}}
这是我的子组件,由根组件添加。它必须 self 毁灭:
@Component({
selector: 'convertors',
template: "<button (click)="deleteComponent()" >Delete</button>"})
export class someComponent{
deleteComponent(){
/*How could I implement this function?*/
}
}
我如何实现方法deleteComponent()? 谢谢!
最佳答案
好的,我的解决方案使用消息服务。看here如果你不知道它的作用。这很简单。 首先,我为任何动态组件分配唯一的 id。接下来,我在 map 中保留组件及其 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;
}
其次, subview 上的事件点击通过消息服务将其 id 发送给父 View 。考虑到在子级中声明的“componentId:string”。但它是在父级中分配的!
<a (click)="deleteComponent()"></a>
private componentId: string;
deleteComponent() : void {
this.messageService.sendMessage(this.componentId);
}
最后,我们的父级从消息服务接收 id。接下来,它在 map 中查找 child 的引用。最后,我们调用原生方法 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);
}
如果知道如何改进这个解决方案请写在评论中。我有一种感觉,它可能会更好。谢谢。
关于angular2-components - Angular 2.动态创建的组件如何自行调用destroy方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44187651/