简体   繁体   English

使用 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.我有一个指令,当您悬停元素时实现滑块,如果您在悬停图像时访问此站点,该指令使其他图像绝对为主图像并启用箭头以滑动到下一个图像,唯一的问题是我有一个 appLazyLoadWithLoading 指令,当图像在页面中可见且不在屏幕外时加载图像,并在加载之前添加加载,我正在寻找一种将指令添加到创建的 img 元素的方法。

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.通过这种方式添加了 img 元素,但我无法将我的指令添加到它尝试这种方式和 $compile 并且它们没有工作。

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

It is possible not using Renderer2 but by using dynamic component loading .可以不使用Renderer2而是使用动态组件加载

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.基本上,不是创建一个img html 元素,而是创建一个包含img元素的组件,其中包含您想要的任何指令,然后动态加载该组件。

Here's an example StackBlitz这是一个示例StackBlitz

At moment till Angular v12, you can not add components dynamically in DOM.在 Angular v12 之前,您不能在 DOM 中动态添加组件。

A solution Can be,一个解决方案可以是,

  1. Create a component with selector [appLazyLoadWithLoading]使用选择器[appLazyLoadWithLoading]创建组件
  2. Convert this component to Angular Elements.将此组件转换为 Angular Elements。
  3. Now you can use converted components dynamically.现在您可以动态使用转换后的组件。

Basically what happens is Angular Element help to covert your components to Web Component.基本上发生的事情是 Angular Element 帮助将您的组件转换为 Web 组件。 So when you add a particular selector to DOM, the specific web component will kick in, and you will see desired behavior on HTML.因此,当您将特定选择器添加到 DOM 时,特定的 Web 组件将启动,您将在 HTML 上看到所需的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM