![](/img/trans.png)
[英]parent component accesses one of its child via ViewChild but it is always undefined
[英]ViewChild returns undefined while returning from child component to parent component
我宣布ViewChild
的對象DateRangePickerComponent
。 過去 7 天是默認選擇的日期范圍。 但我在ngAfterViewInit()
生命周期鈎子內updateDateRange()
的函數updateDateRange()
中將其更新為過去 30 天。 但是當我導航到子組件並導航回父組件時,我調用了updateDateRange()
函數將日期范圍從默認的Last 7 Days更新到Last 30 Days 。 但是DateRangePickerComponent
的對象變得undefined
因為視圖沒有啟動而是視圖改變了。
總之
首先,我在父頁面中。 目前父頁面啟動視圖時我聲明了一個DateRangePickerComponent對象。 並使用我的自定義 updateDateRange() 函數更改選定的日期范圍。 直到現在它的工作正常。 但是當我導航到子組件並返回到父組件時,之前創建的 DateRangePickerComponent 對象變得未定義。 這就是情況。
那么我該如何解決這個問題。 代碼如下。
父html文件`
<div>
**main block of code**
**injecting Child component**
<app-child-component (directiveBack)="navigatePage(pageSwitch.ViewPage, $event)"></app-child-component>
</div>
父 ts 文件`
parent class{
@ViewChild(DateRangePickerComponent) private permissionDateRange: DateRangePickerComponent;
searchFilter: ExampleInputDto;
constructor(injector: Injector){
super(injector);
this.searchFilter = new ExampleInputDto();
this.searchFilter.fromDate = moment().subtract(30, 'days');
this.searchFilter.toDate = this.appConst.calenderSettings.daterangePickerOptions.toDate; //appConsts holds the constant files used in application.
}
ngAfterContentInit(): void {
}
ngAfterViewInit(): void {
updateDateRange();
}
updateDateRange(): void {
this.permissionDateRange.datePicker.setStartDate(this.searchFilter.fromDate.toDate());
this.permissionDateRange.datePicker.setEndDate(this.searchFilter.toDate.toDate());
}
navigatePage(switchEnum: SwitchEnums, data?: any): void {
if (data) {
this.searchFilter.fromDate = moment().subtract(30, 'days');
this.searchFilter.toDate = this.appConst.calenderSettings.daterangePickerOptions.toDate;
this.updateDateRange();
}
}
}
`
子 ts 文件
`
child class{
@Output() directiveBack: EventEmitter<>;
constructor(){}
navigateBack(): void { //this function is called after clicking back button in child html
this.directiveBack.emit(null)
}
}
`
我會嘗試使用靜態 ViewChild:
@ViewChild(DateRangePickerComponent, { static: true }) private permissionDateRange: DateRangePickerComponent;
searchFilter: ExampleInputDto;
使用靜態查詢 (static: true),一旦創建視圖,查詢就會解析,但在更改檢測運行之前。 但是,結果永遠不會更新以反映對視圖的更改,例如對 ngIf 和 ngFor 塊的更改。
Moover 您可以在這種方法ngAfterViewInit
ngOnInit
更改為ngOnInit
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.