简体   繁体   中英

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:

<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:

@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 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 .

@ViewChild ('child', {static: false }) coursesList!: CoursesListComponent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM