0

I am trying to avoid adding duplicate dynamic component in the angular application. I do not know how to do it. If any one know help to resolve this issue.

enter image description here

home.component.html:

<p>And I'm Lucas Simões</p>

<button type="button" (click)="addComp()">Add component</button>

<div #myDiv></div>

home.component.ts

import { Component, inject, OnInit,ViewChild,ViewContainerRef } from '@angular/core';
import { DataComponent } from '../data/data.component';
@Component({
 selector: 'app-home',
 templateUrl: './home.component.html',
 styleUrls: ['./home.component.css'],
 standalone: true,
})
export class HomeComponent implements OnInit{
@ViewChild('myDiv', {static:false, read: ViewContainerRef}) ele!:any;
ngOnInit(){ 
}

 addComp(){
  this.ele.createComponent(DataComponent);
 }

}

stackblitz

2
  • Your question is not clear. What do you mean by avoid adding duplicate dynamic component? Commented Jun 27 at 12:17
  • @WeberK.: Check the image or Stacklitz demo link. You can understand easily. Also Your concept iss not working: stackblitz.com/edit/… Commented Jun 27 at 12:57

1 Answer 1

1

If you want to avoid multiple DataComponent being created in the this.ele ElementRef, you can check before adding a new instance.

import {
  Component,
  OnInit,
  ViewChild,
  ViewContainerRef,
  ComponentRef
} from '@angular/core';
import { DataComponent } from '../data/data.component';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  standalone: true,
})
export class HomeComponent {
  @ViewChild('myDiv', { static: false, read: ViewContainerRef }) ele!: any;
  private componentref?: ComponentRef<DataComponent>;

  addComp() {
    if (this.componentref == null) {
      this.componentref = this.ele.createComponent(DataComponent);
    }
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

A simple check was added
Any other way is there?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.