Tips on preventing the duplication of component instances in your project

Check out the plunker link to see that the child component "Loader" is being loaded multiple times every time the button is clicked. How can I prevent creating multiple instances of the same component? I want the new instance to replace the existing one when the button is clicked. Any suggestions on how to achieve this?

Here is the code snippet of the parent component:

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

      });

  }


}

Answer №1

Remember to store the reference cmpRef and invoke cmpRef.destroy() before initializing a new instance.

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

      });

  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Does nestjs support typescript version 3.x?

Currently embarking on a new project using Nestjs. I noticed in one of its sample projects, the version of Typescript being used is 2.8. However, the latest version of Typescript is now 3.2. Can anyone confirm if Nest.js supports version 3.x of Typescrip ...

Making retries with the RetryWhen filter in Angular 2 RxJS Observables when encountering errors in the status

I'm currently working with the Angular 2 HTTP library, which returns an observable. I'm trying to set up a retry mechanism for specific error statuses/codes. The problem I'm facing is that when the error status is not 429, Observable.of(err ...

Does a typescript definition file exist for Apple MapKit JS?

Before embarking on creating one, I'm curious if anyone has come across a typescript definition file (.d.ts) for Apple MapKit JS? ...

Running Jest tests with TypeScript involves executing the tests twice: once for TypeScript files and once for JavaScript files

I’ve recently started writing tests using TypeScript and Jest, but I’m running into an issue where the tests are being executed twice – once for the TS files and then again for the compiled JS files. While the TypeScript tests are passing without an ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

What steps can be taken to eliminate a npm install error?

I have been attempting to execute the following project: https://github.com/kentcdodds/react-in-angular This repository serves as an illustration of incorporating React into AngularJS. It consists of three tags that demonstrate the process of transitio ...

Encountering an issue where the module '@angular/compiler-cli/ngcc' cannot be located in Angular 8

Upon attempting to run ng serve from my terminal window, I encountered the following error: An unhandled exception occurred: Cannot find module '@angular/compiler-cli/ngcc' Here is an excerpt from my package.json file: { "name": "ProjectDeta ...

Unresolved (waiting for response) unidentified

I encountered a perplexing error in Chrome and I am unable to identify its source: https://i.sstatic.net/f9Blt.png The only clue I have is that after refactoring approximately 10,000 lines of code, this error surfaced. It occurred during the middle of the ...

Having trouble uploading images using Ionic/Angular to a PHP script

I've been working on incorporating image uploading functionality into my Ionic app. Despite reading multiple tutorials, I haven't been able to get it up and running successfully. I'm specifically aiming for the app to work smoothly in a web ...

How can I effectively utilize the Metamask SDK with TypeScript?

Currently, I am in the process of developing a webpack+pnpm+typescript+react website. All the versions being used are LTS and my preferred IDE is VSCode. According to the guide provided by Metamask here, it seems like I need to follow these steps: npm i @m ...

Creating a consistent template for typing TypeScript generics

Is it possible to modify a generic function so that it can accept an unlimited number of arguments and concatenate them with .'s? This function should be able to handle nested objects with any number of keys. The current code snippet works when manua ...

Using Angular to create a nested routerLink within a routerLink

Is there a way to dynamically change the content of a page loaded using router link without duplicating the HTML code for the header and footer sections each time? I want to navigate between different pages with routerLink and have only the main content ar ...

The <a> tag does not lead to a different webpage and cannot be clicked on

I have developed a web component that includes a method to generate a copyright string: '<p>Copyright © 2020 John Doe<a href="https://www.example.com">. Terms of Use</a></p>' After creating the string, I conver ...

The specified control name formControlName in the Angular reactive form cannot be located

Having encountered this issue multiple times on Stack Overflow without any success, I am reaching out for help to identify what I might be doing wrong. In my component : ngOnInit() { this.companyCreatForm = this._formBuilder.group({ name: [null, ...

The necessary package required for my library is missing (@angular/material/core not found)

I have developed a custom Angular library called @foo/bar, and it has the following dependencies: "peerDependencies": { "@angular/common": "^10.0.14", "@angular/core": "^10.0.14" }, "depend ...

Styling does not affect an Angular component that is injected into an iframe

I am facing an issue with styling in an iframe when trying to append my own angular component. Despite various attempts, I have been unsuccessful in getting the styling to apply to the component within the iframe. Upon loading the iframe, I use JavaScript ...

Lite-server experiences a denial of service problem

After installing lite-server today, a vulnerability to denial of service was detected. I am concerned about the impact it may have on my system if I continue using lite-server. Is there a solution available to address this issue? ...

Facebook sharing woes: Angular app's OG meta tags fail to work properly

Trying to figure out how to properly use og tags for the first time. I'm working on an Angular application and need to share my app link on Facebook with all the necessary tag information included. In my index.html file, I've inserted the follow ...

The interactive Material UI Radio buttons are not responding to click events due to dynamic generation

Click here to see the demo in action: https://codesandbox.io/s/material-demo-9fwlz I expected this code to produce checkable radio elements, but it doesn't seem to be working correctly. Can anyone identify what might be causing the issue? This code s ...

Utilize the unique key generated by Firebase for assigning values to ng-select elements

Version of Angular: 8.2.12 My goal: I am looking to create a form where users can add a new product and choose packaging products for it from another collection. These packaging products may have changing attributes like price, so I aim to link them using ...