簡體   English   中英

Angular 4 init子組件輸入

[英]Angular 4 init child component input

我的父組件html包含以下行以默認值為maxPrice調用子組件:

 <app-filter-events [maxPrice]='_maxPrice'></app-filter-events> 

在實例化子組件之前,父組件通過調用API來獲取maxPrice,這是代碼:

 constructor(private _dataService: DataService) { this._dataService.getEventsByCriteria(this._filterCriteria).subscribe(res => this._maxPrice = res); } 

問題在於子組件中未定義maxPrice。 我猜問題出在對API的異步調用上,但是我不知道要解決它。

謝謝

編輯:我的問題是,如果未定義maxPrice,則不隱藏子組件,而是在實例化子組件之前設置maxPrice。

_maxPrice仍未定義時,您無法實例化app-filter-event組件:

<app-filter-events *ngIf='_maxPrice' [maxPrice]='_maxPrice'></app-filter-events>

在調用之前將變量設置為false,在異步完成后將其設置為true是非常簡單的。 在完成之前,您不希望將組件加載到dom中。

<div *ngIf="maxPriceBoolean">
  <app-filter-events [maxPrice]='_maxPrice'></app-filter-events>
</div>

只需使用*ngIf

<app-filter-events *ngIf='_maxPrice' [maxPrice]='_maxPrice'></app-filter-events>

要么

<ng-container *ngIf="_maxPrice">
   <app-filter-events [maxPrice]='_maxPrice'></app-filter-events>
</ng-container>

constructor@Input()之前執行,因此綁定的Input值在構造函數塊中未定義,使您的組件實現OnInit並在ngOnInit()方法中訪問@Input()變量,即可使用。

使用異步管道:

<app-filter-events [maxPrice]='_maxPrice$ | async'></app-filter-events>

組件代碼

    _maxPrice$: Observable<number>;
   constructor(private _dataService: DataService) {
     this._maxPrice$ = this._dataService.getEventsByCriteria(this._filterCriteria)
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM