代码之家  ›  专栏  ›  技术社区  ›  Renjith

Angular 6+从文档中获取具有类名的元素并更改样式

  •  1
  • Renjith  · 技术社区  · 6 年前

    我的HTML页面中有一组“选项卡”。它们只不过是带有类名“tab”的“div”。我的目的是一次显示一个选项卡,并使用“下一步”和“上一步”按钮访问其他选项卡。HTML代码如下所示。

    <div class="container">
      <div *ngFor="let question of questionList;let i = index" class="questionBox tab">
    
    
        {{question.question.query}}
    
        <br>
        <div *ngFor="let option of question.options">
          <input type="radio" value="{{option.id}}" name="radio_{{i}}" [(ngModel)]="question.selected.id">{{option.text}}
          <br>
        </div>
        {{question.selected | json}}
    
        <br>
        <br>
        <!--TO DO -->
        <input type="button" class="btn btn-primary" value="Previous">
        <!--TO DO -->
        <input type="button" class="btn btn-primary nxtButton" value="Next">
      </div>
      <input type="button" class="btn btn-success btn-block" value="Submit">
    </div>
    

    最初,所有选项卡都是用CSS隐藏的。

    .tab{
        display: none; 
    }
    

    在页面初始化时,必须显示第一个选项卡,其余选项卡隐藏。 showTab() 组件类中的方法就是为了达到这个目的。shotTab方法接受一个“数字”,表示要显示的选项卡的索引。

      public showTab(n: number){
    
        let tabElements = document.getElementsByClassName("tab");
        let tabToDisplay = tabElements.item(n) as HTMLElement;
        tabToDisplay.style.display="block";
      }
    

    要显示第一个选项卡,将从调用showTab()方法 组件的方法。但是这条线 让tabElements=document.getElementsByClassName(“tab”); 不会返回任何结果。i、 e.长度 tabElements 是0。因此,应用程序将失败,原因是“ ".

    AppComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'style' of null
        at AppComponent.push../src/app/app.component.ts.AppComponent.showTab (app.component.ts:25)
        at AppComponent.push../src/app/app.component.ts.AppComponent.ngOnInit (app.component.ts:18)
        at checkAndUpdateDirectiveInline (core.js:9243)
        at checkAndUpdateNodeInline (core.js:10507)
        at checkAndUpdateNode (core.js:10469)
        at debugCheckAndUpdateNode (core.js:11102)
        at debugCheckDirectivesFn (core.js:11062)
        at Object.eval [as updateDirectives] (AppComponent_Host.ngfactory.js? [sm]:1)
        at Object.debugUpdateDirectives [as updateDirectives] (core.js:11054)
        at checkAndUpdateView (core.js:10451)
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   tao    6 年前

    使命感 showTab() 在里面 ngOnInit() 意味着在初始化子级之前调用它。

    你需要使用 ngAfterViewInit()

    全部名单 component lifecycle hooks .