Home > database >  How to select multiple dom elements in angular?
How to select multiple dom elements in angular?

Time:01-29

<div   >
  <div  (mouseenter)="sepin(sepinout)" (mouseleave)="sepout(sepinout)"><a href="#in">HOME</a></div>
  <div  #sepinout></div>
  <div  (mouseenter)="sepin(sepinout)" (mouseleave)="sepout(sepinout)"><a href="#ab">SOBRE MI</a></div>
  <div  #sepinout></div>
  <div  (mouseenter)="sepin(sepinout)" (mouseleave)="sepout(sepinout)"><a href="#his">HISTORIA</a></div>
  <div  #sepinout></div>
  <div  (mouseenter)="sepin(sepinout)" (mouseleave)="sepout(sepinout)"><a href="#ex">EXPERIENCIA</a></div>
  <div  #sepinout></div>
  <div  (mouseenter)="sepin(sepinout)" (mouseleave)="sepout(sepinout)"><a href="#cont">CONTACTO</a></div>
  <div  #sepinout></div>
</div>
export class NavBarComponent {
  sepin(sepinout: HTMLElement){
    sepinout.style.translate = "0px"
  }

  sepout(sepinout: HTMLElement){
    sepinout.style.translate = "-2000px"
  }
}

The selector tag #sepinout only selects one element, I don't know how to select several at the same time, and that this function is fulfilled for all the elements of the list

I tried to use the same selector but it doesn't seem to work as the action happens with only one element

CodePudding user response:

You can use document.querySelectorAll('.sep') to select all elements with the class 'sep'.

export class NavBarComponent {
  sepin() {
    const sepinout = document.querySelectorAll('.sep');
    sepinout.forEach(el => {
        el.style.transform = "translate(0px)";
    });
  }

  sepout() {
    const sepinout = document.querySelectorAll('.sep');
    sepinout.forEach(el => {
        el.style.transform = "translate(-2000px)";
    });
  }
}

I hope that helped you, if that helped please give upvote and mark question as solved, Thanks

CodePudding user response:

You can use ViewChildren to get all the elements of your html

<div >
  <div  (mouseenter)="sepin()" (mouseleave)="sepout()"><a href="#in">HOME</a></div>
  <div  #sepinout></div>
  <div  (mouseenter)="sepin()" (mouseleave)="sepout()"><a href="#ab">SOBRE MI</a></div>
  <div  #sepinout></div>
  <div  (mouseenter)="sepin()" (mouseleave)="sepout()"><a href="#his">HISTORIA</a></div>
  <div  #sepinout></div>
  <div  (mouseenter)="sepin()" (mouseleave)="sepout()"><a href="#ex">EXPERIENCIA</a></div>
  <div  #sepinout></div>
  <div  (mouseenter)="sepin()" (mouseleave)="sepout()"><a href="#cont">CONTACTO</a></div>
  <div  #sepinout></div>
</div>

TypeScript

  @ViewChildren('sepinout') sepinouts!: QueryList<any>;

  sepout() {
    this.translateElements('0');
  }

  sepin() {
    this.translateElements('-2000px');
  }

  translateElements(translate: string) {
    this.sepinouts.toArray().forEach((item: any) => {
      item.nativeElement.style.translate = translate;
    });
  }

I hope it helps you

  • Related