Typescript 如何避免创建同一组件的多个实例
请参阅,因为您可以注意到每当单击按钮时,子组件“Loader”都会被加载多次,即每次单击都会创建一个新实例 如何避免创建同一组件的多个实例?我的要求每当单击按钮时,新实例是否应替换现有实例?如何做到这一点 父组件Typescript 如何避免创建同一组件的多个实例,typescript,angular,Typescript,Angular,请参阅,因为您可以注意到每当单击按钮时,子组件“Loader”都会被加载多次,即每次单击都会创建一个新实例 如何避免创建同一组件的多个实例?我的要求每当单击按钮时,新实例是否应替换现有实例?如何做到这一点 父组件 import { Component, ViewChild, ViewContainerRef, ComponentResolver, Injector, AfterViewInit } from '@angular/core'; import {Loader} from './Loa
import { Component, ViewChild, ViewContainerRef, ComponentResolver, Injector, AfterViewInit } from '@angular/core';
import {Loader} from './Loader';
@Component({
selector: 'my-app',
providers: [],
template: `
<div>
<h2>Hello {{name}}</h2>
<input type="button" (click)="onclick($event)" value="Click"/>
<h3>Loading component</h3>
<load></load>
</div>
`,
directives: [Loader]
})
export class App {
constructor(private _injector: Injector, private viewContainer: ViewContainerRef, private _cr: ComponentResolver) {
this.name = 'Angular2 (Release Candidate!)';
console.log("in constructor of App");
}
@ViewChild(Loader, { read: ViewContainerRef }) childContainer;
onclick(event)
{
this._cr.resolveComponent(Loader).then(cmpFactory => {
console.log("Creating component");
this.childContainer.createComponent(cmpFactory,null, this._injector);
let cmpRef = this.childContainer.createComponent(cmpFactory);
cmpRef.instance.ParentID = "55";
});
}
}
从'@angular/core'导入{Component,ViewChild,ViewContainerRef,ComponentResolver,Injector,AfterViewInit};
从“/Loader”导入{Loader};
@组成部分({
选择器:“我的应用程序”,
提供者:[],
模板:`
你好{{name}
加载元件
`,
指令:[加载器]
})
导出类应用程序{
构造函数(private _injector:injector,private viewContainer:ViewContainerRef,private _cr:ComponentResolver){
this.name='Angular2(发布候选!)';
console.log(“在应用程序的构造函数中”);
}
@ViewChild(加载程序,{read:ViewContainerRef})childContainer;
onclick(事件)
{
这个{
日志(“创建组件”);
this.childContainer.createComponent(cmpFactory,null,this.\u injector);
让cmpRef=this.childContainer.createComponent(cmpFactory);
cmpRef.instance.ParentID=“55”;
});
}
}
在创建新实例之前,存储cmpRef
并调用cmpRef.destroy()
onclick(event)
{
this._cr.resolveComponent(Loader).then(cmpFactory => {
if(this.cmpRef) {
this.cmpRef.destroy();
this.cmpRef = null;
}
console.log("Creating component");
//this.childContainer.createComponent(cmpFactory,null, this._injector);
this.cmpRef = this.childContainer.createComponent(cmpFactory);
this.cmpRef.instance.ParentID = "55";
});
}
您能在plunker中更正它吗?建议的更改在plunker中不起作用?plunker中有两种不同的
createComponent
,一种通过喷油器,另一种不通过喷油器destroy()
仅对存储了cmpRef
的文件调用。因此,每次单击都会创建两个组件,但只销毁一个。我注释掉了一个createComponent
理解错误,但即使现在您注意到有两个加载程序组件实例被呈现,即第一个实例在页面加载期间呈现,第二个实例在单击事件期间呈现。如何在页面加载期间避免,即我需要仅在单击事件期间加载?一个是通过AppComponent
模板中的
静态添加的。删除这一行;-)在发布之前,我已经尝试删除该行,在这种情况下,它不会加载任何实例。甚至尝试添加id为“load”的div标记。在这两种情况下,它甚至不加载任何单个实例?