Angular Anchor Directive on element that doesn't exist yet

Viewed 26

I am seeking to do something similar to this example. It uses a helper directive to mark valid insertion points in the template for generated components. However, for my application, the container that should contain the new components (<ng-template adHost>) does not exist until the page is loaded and the user has clicked on a few things.

As far as I can tell, this completely breaks the directive. Angular has no idea where to insert the generated components, and doesn't insert them at all.

How do I work around this problem?

This is a stackblitz of their example.
This is a slightly modified stackblitz of what I'm trying to do.

1 Answers

There are several ways to solve this (assuming your only problem is that your ad-banner.component.ts fails to append the DOM since it's not fully rendered yet).

First things first:  It is important to understand the Angular lifecycle hooks.   In your example you are trying to append an HTML element in the ngOnInit lifecycle hook. This is not tied to the DOM and usually fires before the DOM is rendered.

Moving on to what I would suggest one of these approaches (i prefer the second):

  1. Use the ngAfterViewInit lifecycle hook instead of ngOnInit.    This fires after the DOM is rendered and you can place your elements safely.

  ngAfterViewInit(): void {
    $('#custom-container').append('<ng-template adHost></ng-template>');
    this.loadComponent();
    this.getAds();
  }

  1. Create a component and place the template code inside and then use data binding to rotate your ad content:

    ng generate component ad-component

Hope this helps.

Related