0

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.sstatic.net/obrdM.png

1 Answer 1

0

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.