2016-09-20 21 views
1

所以問題是如何從模板中的子組件中的屬性收集數據到父組件。 父模板看起來是這樣的:如何收集來自子組件的屬性的數據Angular 2

<ion-content> 
    <blocks-banners-slideshow class="contentBlock" [zone]="'main'" [slideOptions]="{loop:true}"></blocks-banners-slideshow> 
    <blocks-catalog-category class="contentBlock" [root]="0"></blocks-catalog-category> 
    <blocks-catalog-topproducts class="contentBlock" [dirs]="[0]" ></blocks-catalog-topproducts> 
</ion-content> 

我有分量的塊,橫幅,幻燈片,塊型錄類,塊,目錄,新產品推薦。 我需要以某種方式循環所有這些組件來收集來自我的父組件中的屬性 - [zone],[root],[dirs]等的數據。

你有什麼想法嗎?

回答

0

您可以通過ViewChild訪問它們。

給您的孩子的名字,或使用類型,而不是:

<ion-content> 
    <blocks-banners-slideshow #bbs class="contentBlock" [zone]="'main'" [slideOptions]="{loop:true}"></blocks-banners-slideshow> 
    <blocks-catalog-category #bcc class="contentBlock" [root]="0"></blocks-catalog-category> 
    <blocks-catalog-topproducts #bct class="contentBlock" [dirs]="[0]" ></blocks-catalog-topproducts> 
</ion-content> 

而在你的組件:

@ViewChild('bbs') bbs1: BlocksBannersSlideshowComponent; 
@ViewChild(BlocksBannersSlideshowComponent) bbs2: BlocksBannersSlideshowComponent; 

@ViewChild('bcc') bcc1: BlocksCatalogCategoryComponent; 
@ViewChild(BlocksCatalogCategoryComponent) bcc2: BlocksCatalogCategoryComponent; 
... 

這些變量都可以訪問此事件後,被解僱:ngAfterViewInit()

或者使用ViewChildren動態添加的組件:

@ViewChildren(BlocksBannersSlideshowComponent) bbsChilds: QueryList<BlocksBannersSlideshowComponent>; 

@ViewChildren(BlocksCatalogCategoryComponent) bccChilds: QueryList<BlocksCatalogCategoryComponent>; 
... 

和訂閱的ngAfterViewInit()裏面那些querylists:

this.bssChilds.changes.subscribe(...); 
+0

IT'IS一個好主意。謝謝。但是如果模板是在網絡服務器dinamicaly上創建的呢? –

+0

你知道如何循環父組件中的組件嗎? –

+0

循環?你想循環什麼組件? – mxii

相關問題