【问题标题】:Angular 6 + get elements with class name from document and change styleAngular 6 +从文档中获取具有类名的元素并更改样式
【发布时间】:2019-05-31 18:38:30
【问题描述】:

我的 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";
  }

为了显示第一个选项卡,从组件的 ngOnInit() 方法调用 showTab() 方法。但 let tabElements = document.getElementsByClassName("tab"); 行不返回任何结果。即 tabElements 的长度为 0。因此应用程序将失败说“Cannot read property 'style' of null”。

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)

【问题讨论】:

  • 在ngAfterViewInit() 中调用showTab() 而不是ngOnInit()。不同之处在于它是在孩子初始化之后运行的。
  • 谢谢……那行得通。请将其发布为答案。

标签: javascript css angular typescript angular6


【解决方案1】:

在ngOnInit() 中调用showTab() 意味着在子项初始化之前调用它。

你需要使用ngAfterViewInit()钩子。

component lifecycle hooks 的完整列表。

【讨论】:

    【解决方案2】:

    根据您的解决方案,我这样解决了我的问题:

    const myHtmlEl = document.getElementsByClassName('my-style').item(0) as HTMLElement;
    myHtmltEl.style.display = 'none';
    

    但我确信我在整个页面中只有一个项目具有我的风格。 否则你应该用 item.length 循环它们。并将样式应用于每个元素。

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 2019-09-13
      • 1970-01-01
      • 2012-08-13
      • 2019-03-14
      • 1970-01-01
      • 2021-12-20
      • 2019-09-10
      • 1970-01-01
      相关资源
      最近更新 更多