如何避免创建同一组件的多个实例

时间:2016-07-18 17:19:01

标签: typescript angular

请参考plunker,因为您可以注意到子组件" Loader"每次单击按钮时都会加载多次,即每次单击时都会创建一个新实例。

如何避免创建同一组件的多个实例?我的要求只要点击按钮,新实例应该替换现有的?怎么做?

父组件

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";  

      });

  }


}

1 个答案:

答案 0 :(得分:2)

在创建新实例之前存储unsigned char *data; size_t n, todo, blksz; blksz = par.round * par.rchan * par.bps; for (;;) { /* read one block */ data = buf; todo = blksz; while (todo > 0) { n = sio_read(hdl, data, todo); if (n == 0) errx(1, "failed"); todo -= n; data += n; } /* write one block */ n = sio_write(hdl, buf, blksz); if (n != blksz) errx(1, "failed"); } 并致电cmpRef

cmpRef.destroy()