【发布时间】: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