在下面,我尝试使用参数('选定')来调用带有传递的参数(字符串)的设置样式,例如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>
最快,效率低下的方法是将模板引用直接发送到控制器,并遍历所有标头并设置样式。
控制器
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
发送给控制器,而不是字符串。