[英]angular ViewChild isnt working inside a ngIf statement
I am trying to show student data in a table according to a selected course我正在尝试根据所选课程在表格中显示学生数据
in my app.componenet.html:在我的 app.componenet.html 中:
<div class="column">
<app-courses-list #child></app-courses-list>
</div>
<div class="column" *ngIf="coursesList?.showStudentComponent">
<app-students-table [selectedCourse]="coursesList.selectedCourse"></app-students-table>
</div>
in my app.componenet.ts:在我的 app.componenet.ts 中:
@ViewChild ('child', {static: true}) coursesList!: CoursesListComponent
in my students-table.componenet.ts:在我的学生-table.componenet.ts 中:
@Input() selectedCourse : string = ''
in my courses-list.componenet.ts:在我的课程-list.componenet.ts 中:
selectedCourse : string = ''
showStudentComponent : Boolean = false
showAngular() : void {
this.selectedCourse = 'Angular'
this.showStudentComponent = true
}
showPython() : void {
this.selectedCourse = 'Python'
this.showStudentComponent = true
}
showJava() : void {
this.selectedCourse = 'Java'
this.showStudentComponent = true
}
showMongo() : void {
this.selectedCourse = 'MongoDB'
this.showStudentComponent = true
}
showAll() : void{
this.selectedCourse = 'All'
this.showStudentComponent = true
}
At this point everything works fine but when I try to nest it inside a ngIf statement - the functionality of the component stops working.此时一切正常,但是当我尝试将其嵌套在 ngIf 语句中时 - 组件的功能停止工作。
The following code is same code as shared so far but nested in an ngIf以下代码与目前共享的代码相同,但嵌套在 ngIf 中
<ng-container *ngIf="homeFlag; else course">
<div class="jumbotron">
<h1 class="display-3">Welcome</h1>
<p class="lead">Software Department!</p>
</div>
</ng-container>
<ng-template #course>
<ng-container *ngIf="coursesFlag; else students">
<app-card></app-card>
</ng-container>
</ng-template>
<ng-template #students>
<div class="row">
<div class="column">
<app-courses-list #child></app-courses-list>
</div>
<div class="column" *ngIf="coursesList?.showStudentComponent">
<app-students-table [selectedCourse]="coursesList.selectedCourse"></app-students-table>
</div>
</div>
</ng-template>
Why possibly is the functionality of the table isn't working anymore?为什么表格的功能可能不再起作用?
Change static
to false
, when you use view child to access an element that is conditionally rendered using ngIf
.当您使用 view child 访问使用
ngIf
有条件地呈现的元素时,将static
更改为false
。
@ViewChild ('child', {static: false }) coursesList!: CoursesListComponent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.