Home > Enterprise >  How can I fetch nodelist with document.querySelectorAll in Angular?
How can I fetch nodelist with document.querySelectorAll in Angular?

Time:12-25

This is a part of an e-commerce app in which customers can select an order and go to checkout. A group of similar buttons that have a data- attribute, with respective extensions to data-something. I am able to implement this well in JavaScript and Html 5. I want to know how to achieve exactly the same using Angular.

    
          <button data-plan="bronze">Select Plan</button>
          <button data-plan="silver">Select Plan</button>
          <button data-plan="gold">Select Plan</button>
          <button data-plan="diamond">Select Plan</button>

Below is JavaScript I wish to implement in Angular,

// Select Plan Logic
    const planButtons = document.querySelectorAll("button[data-plan]");

CodePudding user response:

To interact with HTML elements in Angular and have references on them you should use @ViewChild or @ViewChildren decorators. First one is for only one element and second one for more than one.

When using these decorators you should consider ngAfterViewInit lifecycle method in which you can access references to DOM elements. Under the hood, @ViewChild or @ViewChildren are using document.querySelector and document.querySelectorAll.

Learn and read more about them:

https://angular.io/api/core/ViewChild

https://angular.io/api/core/ViewChildren

  • Related