angularangular-directiveangular-renderer2

Adding directive to an element using Renderer2


I have a directive that implements a slider when you hover the element, If you visit this site when you hover the image the directive makes other images absolute to the main one and enables arrows for sliding to next image, The only problem is that i have a appLazyLoadWithLoading directive that loads images when they are visible in the page and are not in offscreen and adds loading before load and I'm looking for a way to add my directive to created img elements.

let img = this.renderer2.createElement('img');
this.renderer2.setAttribute(img, "src", this.thumbnailMaker(element.url));
this.renderer2.setAttribute(img, "alt", element.name);
this.renderer2.setAttribute(img, "title", element.name);
this.renderer2.appendChild(this.el.nativeElement.parentElement, img);

this way the img element is being added but i cant add my directive to it tryed this way and $compile and they didnt work.

this.renderer.setAttribute(img, "appLazyLoadWithLoading", "work please!");

Solution

  • At moment till Angular v12, you can not add components dynamically in DOM.

    A solution Can be,

    1. Create a component with selector [appLazyLoadWithLoading]
    2. Convert this component to Angular Elements.
    3. Now you can use converted components dynamically.

    Basically what happens is Angular Element help to covert your components to Web Component. So when you add a particular selector to DOM, the specific web component will kick in, and you will see desired behavior on HTML.