khaled mahmoud
khaled mahmoud

Reputation: 97

use parameter to access predefined child

here in the below I'm trying to user the parameter ('selected') to call set style with the passed parameter (string) like onClick('firstheader')

I hope could explained my point

  @ViewChild('firstheader', { static: false }) firstheader: ElementRef;
  @ViewChild('secheader', { static: false }) secheader: ElementRef;
  @ViewChild('thirdheader', { static: false }) thirdheader: ElementRef;



  onClick(selected) {

    this.firstheader.nativeElement.style.display = 'none'
    this.secheader.nativeElement.style.display = 'none'
    this.thirdheader.nativeElement.style.display = 'none'



    this.selected.nativeElement.style.display = 'flex' <-- here (selected)

  }

the HTML

<div class="header__bullets-container">
    <div class="header__bullet" (click)="onClick('firstheader')"></div>
    <div class="header__bullet" (click)="onClick('secheader')"></div>
    <div class="header__bullet" (click)="onClick('thirdheader')"></div>
</div>

Upvotes: 0

Views: 23

Answers (1)

Barremian
Barremian

Reputation: 31115

The quickest and inefficient way would be to send the template reference directly to the controller and loop through all the headers and set the style.

Controller

headers = [];
@ViewChild('firstheader', { static: false }) firstheader: ElementRef;
@ViewChild('secheader', { static: false }) secheader: ElementRef;
@ViewChild('thirdheader', { static: false }) thirdheader: ElementRef;

ngAfterViewInit() {
  this.headers = [this.firstheader, this.secheader, this.thirdheader];
}

onClick(selected: any) {
  this.headers.forEach(header => {
    if (header.nativeElement == selected) {
      selected.style.display = 'flex';
    } else {
      header.nativeElement.style.display = 'none';
    }
  });
}

Template

<div class="header__bullets-container">
  <div class="header__bullet" (click)="onClick(firstheader)"></div>
  <div class="header__bullet" (click)="onClick(secheader)"></div>
  <div class="header__bullet" (click)="onClick(thirdheader)"></div>
</div>

Notice the lack of quotation marks in the template. We are sending the HTML element to the controller instead of a string.

Upvotes: 1

Related Questions