使用Angular将div动态添加到具有相同类的元素

问题描述

我需要向所有具有类'.cart-list-value .delete-product'的元素添加一个包含背景图像的类.cart-list-item的div。我可以使用类.carl-list-item 获取所有元素,但是当我添加新元素时,它只是添加到了最后一个元素。

export class ShopViewCartViewComponent implements OnInit {
  constructor(
    private renderer: Renderer2,private elem: ElementRef,protected cartService: CartService  <BaseCartItem>
  ) {}

  ngOnInit(): void {}

  ngAfterViewInit() {
    const child = document.createElement("div");
    child.addEventListener('click',this.onClick.bind(this));
    child.classList.add('cart-list-value','delete-product');
    
    const elements = this.elem.nativeElement.querySelectorAll('.cart-list-item');
    elements.forEach(element => {
      this.renderer.insertBefore(element,child,element.childNodes[0]);
    });
    console.log(elements);
  }

    onClick(event) {
    console.log(event);
  }
}``` 

[here you can see what is the result][1]


  [1]: https://i.stack.imgur.com/obrdM.png

解决方法

您正在创建一个元素(const child = document.createElement("div")),然后将相同的 reference 传递给所有容器元素(.cart-list-item)。 / p>

因此,它首先移入第一个元素,然后随着循环的进行,将相同元素(const child...移到下一个容器中。

因此,只需创建该循环内的子元素,即可为每个容器创建一个新元素。像这样:

ngAfterViewInit() {
      
  const elements = this.elem.nativeElement.querySelectorAll('.cart-list-item');

  elements.forEach(element => {
    let child = document.createElement("div");
    child.addEventListener('click',this.onClick.bind(this));
    child.classList.add('cart-list-value','delete-product');

    this.renderer.insertBefore(element,child,element.childNodes[0]);
  });

  console.log(elements);
}