Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!");
like image 574
Behnam Aminazad Avatar asked Apr 06 '26 20:04

Behnam Aminazad


2 Answers

It is possible not using Renderer2 but by using dynamic component loading.

Basically, instead of creating an img html element, create a component which includes an img element inside it, with whatever directives you want, and then load that component dynamically.

Here's an example StackBlitz

like image 100
Aviad P. Avatar answered Apr 09 '26 11:04

Aviad P.


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.

like image 41
Pankaj Parkar Avatar answered Apr 09 '26 13:04

Pankaj Parkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!