0

I'm dynamically creating a component, and I'd like to delete it after 1 second.

I want to do something like that

  ngOnInit(): void {
    const time = timer(2000);
    time.subscribe(() => {
       REMOVE YOURSELF / THIS COMPONENT
    });
  }
4
  • How are you creating your component exactly ? Please provide some code. Commented Sep 6, 2018 at 10:56
  • I want to generate them using loops Commented Sep 6, 2018 at 11:01
  • Any reason why you're not just using ng-if? Commented Sep 6, 2018 at 11:01
  • @Wojtar again, please provide some code. There are several ways to create dynamic components, without even counting what you consider yourself as "dynamic". Commented Sep 6, 2018 at 11:02

1 Answer 1

1

Make a directive for component holder for dynamic component as below:

import { Directive, ViewContainerRef } from "@angular/core";

@Directive({
    selector: '[component-holder]',
})
export class DynamicComponentDirective {
    constructor(public viewContainerRef: ViewContainerRef) { }
}

Use ViewChild to import it to your component as below:

@ViewChild(DynamicComponentDirective ) dynamicComponentDirective : DynamicComponentDirective ;

After creating some dynamic component, you can remove it as below.

this.viewContainerRef = this.dynamicComponentDirective.viewContainerRef;
this.viewContainerRef.clear();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.