使用参数访问预定义子项

问题描述 投票:0回答:1

在下面,我尝试使用参数('选定')来调用带有传递的参数(字符串)的设置样式,例如onClick('firstheader']

我希望可以解释我的观点

  @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)

  }

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>
angular
1个回答
0
投票

最快,效率低下的方法是将模板引用直接发送到控制器,并遍历所有标头并设置样式。

控制器

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';
    }
  });
}

模板

<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>

注意模板中没有引号。我们正在将HTMLElement发送给控制器,而不是字符串。

© www.soinside.com 2019 - 2024. All rights reserved.