I have two components (1-app-student-list 2-app-student-detail).
I want to use student-detail
in the student-list
like the following :
app-student-detail.html
<p>Student Detail Component is here ....</p>
app-student-detail.ts
export class StudentDetailComponent {
showDetail() {
alert("We are in student-detail...");
}
}
app-student-list.html
<p>Student List Component is here ....</p>
<app-student-detail></app-student-detail>
app-student-list.ts
export class StudentListComponent implements OnInit {
@ViewChild(StudentDetailComponent, { static: true }) studentDetail: StudentDetailComponent;
constructor() { }
ngOnInit() {
}
showDetail() {
this.studentDetail.showDetail();
}
}
In the showDetail
method I want to call a method of StudentDetailComponent
named showDetail
And finally, I want to use student-list in the AppComponent
app.component.ts
export class AppComponent {
public isShow = false;
@ViewChild(StudentListComponent, { static: true }) studentList: StudentListComponent;
title = 'AngualrViewChild';
showDetail() {
this.isShow = true;
this.studentList.showDetail();
}
}
app.component.html
<p>App Component is here ....</p>
<app-student-list *ngIf="this.isShow"></app-student-list>
<hr />
<button type="button" (click)="this.showDetail()">
Show Detail
</button>
When I call the showDetail
method of StudentListComponent
I get the following Error :
AppComponent.html:6 ERROR TypeError: Cannot read property 'showDetail' of undefined
Note: When I remove ngIf
above it will work perfectly