Angular - Как уничтожить динамически компонент нажатием кнопки - PullRequest
0 голосов
/ 30 июня 2019

Я использую это для динамического создания компонента в угловых:

addComponent() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
    const viewContainerRef = this.injectComp.viewContainerRef;
    const compRef = viewContainerRef.createComponent(componentFactory);
    compRef.instance.someProperty = "some data";
}

Таким образом, каждый раз, когда метод выполняется, создается новый экземпляр компонента. Там все отлично, но мой вопрос:

Как уничтожить эти созданные компоненты из самого ChildComponent с помощью события нажатия кнопки?

1 Ответ

2 голосов
/ 30 июня 2019

1) Вы можете отслеживать компонент или весь компонент в переменной или в объекте и уничтожать их: -

2) Или уничтожить предыдущий компонент при загрузке нового в DOM, сохранив последнюю ссылку и .destroy() их перед вставкой нового.

.html

 <ng-container #dynamicComponentContainer id="dynamicComponentContainer"></ng-container>

.ts

         let componentRef = this.componentFactoryResolver.resolveComponentFactory(cmptName).create(this.injector);

                // check for duplicates and update with new one
             //   this.checkForDuplicateCmp(componentRef);

                componentRef.instance['inputdata'] = initCmpInputdata;
                let indexView = this.dynamicComponentContainer.length;
                this.dynamicComponentContainer.insert(componentRef.hostView, indexView);

      // keep refrence of lastComponent added to DOM
            this.lastComponent = componentRef;


  public remove component(){
    // destroy components as on click
      this.lastComponent.destroy();
     //or
     for (var j = 1; j < this.dynamicComponentContainer.length; j++) {
          this.dynamicComponentContainer.remove(j);  //or pass j 
      }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...