在Angular的ViewChild上添加和删除元素类

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

我的应用程序中有选项卡,活动选项卡必须与用户级别相对应。我创建了一个viewChild来添加其活动类,但未成功,并且出现以下错误:

ERROR TypeError: Cannot read property 'querySelector' of undefined
    at TrainingComponent.push../src/app/views/training/training.component.ts.TrainingComponent.ngAfterViewInit 

我的组件:

  @ViewChild('tabExplorator') tabExplorator: ElementRef;
  @ViewChild('tabEspecialist') tabEspecialist: ElementRef;

  constructor(public timeguard:TimeguardService, public router: Router,  public progressbar:ProgressBarService, public geo: GeolocationService, public dl: DatalayerService<GameDimensionSet>, public database: DatabaseService < Fase > , public auth: AuthService) {}

  ngAfterViewInit () {
    //assigning an element to a variable
    let tabExplorator = this.tabExplorator.nativeElement.querySelector('tabExplorator')
    let tabEspecialist = this.tabEspecialist.nativeElement.querySelector('tabEspecialist')

    if(this.auth.User.nivel == 'EXPLORADOR' && tabExplorator.classList.contains('active')){
      tabExplorator.classList.remove('active')
      tabEspecialist.classList.add('active')
    }

  }

我的HTML:

 <ul class="tabs ranking-letra-tabs tabs-icon">
      <li class="tab col s3 cor-explorador alinha-texto">
        <a href="#ranking-nivel1" #tabExplorator>
          <div>
            <i class="material-icons cor-estrelas tabs-icon">star</i>
          </div>
          <div class="">
            {{NIVEL1}}
          </div>
        </a>
      </li>

      <li class="tab col s3 cor-especialista alinha-texto">
        <a href="#ranking-nivel2" #tabEspecialist>
          <div>
            <i class="material-icons cor-estrelas estrela-tabs-1">star</i>
            <i class="material-icons cor-estrelas estrela-tabs-2">star</i>
          </div>
          <div>
            {{NIVEL2}}
          </div>
        </a>
      </li>
    </ul>

根据文档,我正在使用物化:

“显示与带有ID的标签相对应的标签内容”

instance.select('tab_id');

能帮上忙吗?

angular typescript tabs materialize viewchild
1个回答
0
投票

您可以将Renderer2Renderer2一起使用来切换元素类。尝试以下]]

ElementRef

工作示例:import { Component, ViewChild, ElementRef, Renderer2 } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = 'Angular'; @ViewChild('tabExplorator') tabExplorator: ElementRef; constructor(private renderer: Renderer2) { } toggleBackground() { const active = this.tabExplorator.nativeElement.classList.contains('active'); this.renderer[active ? 'removeClass' : 'addClass'](this.tabExplorator.nativeElement, 'active'); } }

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