-3

Hi I have a general question is it okay to write JavaScript code in angular (in my case for dom manipulation)

Here is an example of what i would use.

Thanks in Advance.

document.querySelectorAll('div.links a').forEach(function(item) {
  const tag = window.location.href.indexOf('content') > -1 ? 'hello' : 'hai';
  const href = `${item.getAttribute('href')}${brand}`;
  item.setAttribute('href', href);
});
Acuao
  • 671
  • 4
  • 15
Hel_UI
  • 115
  • 1
  • 1
  • 7
  • 4
    Is your question whether it's okay to use JavaScript with Angular (answer: yes), whether it's okay to use direct DOM manipulation in Angular (answer: not usually), or "please help converting this JavaScript code to angular code" (off-topic for this site, and note that Angular is a framework, not a programming language). – T.J. Crowder Oct 29 '20 at 13:47
  • @T.J.Crowder So DOM manipulation code which I have written can be written using angular methods can help in writing that code using angular methods. – Hel_UI Oct 29 '20 at 13:51
  • [Why is “Can someone help me?” not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) What is your actual question? – Thomas Sablik Oct 29 '20 at 13:57
  • My angular is a little rusty, but from what I remember, I think most of what is in your code snippet could be done in the template in a more declarative way. Using querySelector and setting attributes via explicit JS is an older jQuery-ish style for which Angular provides more modern ways to do things. My understanding is that explicit DOM manipulation still has a place in Angular for widgets and detailed low-level dom work, but most of the time the templates and the data-binding is the way to go. – xdhmoore Oct 30 '20 at 07:04

1 Answers1

3

You should access to dom elements using angular properties such as ElementRef/ViewChild like it says on the answer here: Access to dom elements

FLiotta
  • 151
  • 6