Dynamically add a div to elements with the same class using Angular

912 views Asked by At

I need to add a div with class '.cart-list-value .delete-product', that contains a background image, to all elements that have the class .cart-list-item. I was able to get all the elements with class .carl-list-item , but when I add the new element, it just added to the last element.

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
1

There are 1 answers

0
Daniel Guzman On BEST ANSWER

You're creating one element ( const child = document.createElement("div") ) then passing the same reference to all of your container elements ( .cart-list-item ).

So, it first move into the first element, then as the loop goes you take the same element ( const child... ) and move it to the next container.

So, just create that child element inside the loop, so you'll be create one new element for each container. Like this:

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);
}