2017-06-03 94 views
2

我正在嘗試開發一個傳送帶。將屬性傳遞給ng內容中的組件(在標記所在的組件中不可用的屬性)

期望的最終結果應該是開發人員只需在一個地方(比如說app.component.html)將整個標記寫入options屬性,然後輪播將接管。

問題是,從carousel.component我需要在carousel-item.component(性質app.component應該沒什麼關係......但所有的標記是app.component.html)設置一些屬性。

我該如何做到這一點?

app.component.html:

<carousel [options]="myOptions"> 
    <carousel-item *ngFor="let item of items"> 
     <img [src]="item.image" alt="" /> 
    </carousel-item> 
</carousel> 

<hr /> 

<carousel [options]="myOptions2"> 
    <carousel-item *ngFor="let item of items"> 
     <img [src]="item.image" alt="" /> 
    </carousel-item> 
</carousel> 

carousel.component.html:

<div class="carousel-stage"> 
    <ng-content></ng-content> 
</div> 

carousel-item.component.html:

<ng-content></ng-content> 

回答

1

我認爲唯一的解決辦法是@ContentChildren()

走在我carousel.component.ts

import { ContentChildren, ... } from '@angular/core'; 

// ... 

export class CarouselComponent implements AfterContentInit { 
    @ContentChildren(ItemComponent) carouselItems; 

    ngAfterContentInit() { 
    this.carouselItems.forEach((item: ItemComponent, currentIndex) => { 
     // Do stuff with each item 
     // Even call item's methods: 
     item.setWidth(someComputedWidth); 
     item.setClass(someClass); 
    } 
    } 
} 

然後,在carousel-item.component.ts:顯然

export class ItemComponent implements OnInit, OnDestroy { 
    @HostBinding('style.width') itemWidth; 
    @HostBinding('class') itemClass; 
    @HostBinding('@fade') fadeAnimationState; 


    setWidth(width) { 
    this.itemWidth = width + 'px'; 
    } 
    setClass(class) { 
    this.itemClass = class; 
    } 
    setAnimationState(state) { 
    this.fadeAnimationState = state; 
    } 
} 

,我甚至可以結合動畫與觸發@ HostBinding。我認爲@HostBingind()被設計爲只能使用標準的HTML屬性(樣式,類等),但似乎我實際上可以綁定任何東西(從字面上來看)。

有沒有人有更好的解決方案?在我接受我自己的答案之前...

+1

感謝您分享此內容。這是正確的做法,國際海事組織。對於另一個有點相似的參考,您可以看看Ag-Grid團隊如何使用跨列進行列配置:[ag-grid-angular component](https://github.com/ag-grid/ag-grid-angular/) blob/master/src/agGridNg2.ts),[ag-grid-column組件](https://github.com/ag-grid/ag-grid-angular/blob/master/src/agGridColumn.ts)。 '@ ContentChildren'在沒有'ng-content'的情況下使用來獲取和使用子元素進行配置。 –

相關問題