I am trying to show student data in a table according to a selected course
in my app.componenet.html:
<div >
<app-courses-list #child></app-courses-list>
</div>
<div *ngIf="coursesList?.showStudentComponent">
<app-students-table [selectedCourse]="coursesList.selectedCourse"></app-students-table>
</div>
in my app.componenet.ts :
@ViewChild ('child', {static: true}) coursesList!: CoursesListComponent
in my students-table.componenet.ts :
@Input() selectedCourse : string = ''
in my courses-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.
The following code is same code as shared so far but nested in an ngIf
<ng-container *ngIf="homeFlag; else course">
<div >
<h1 >Welcome</h1>
<p >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 >
<div >
<app-courses-list #child></app-courses-list>
</div>
<div *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?
CodePudding user response:
Change static
to false
, when you use view child to access an element that is conditionally rendered using ngIf
.
@ViewChild ('child', {static: false }) coursesList!: CoursesListComponent