2017-09-28 129 views
1

我有這樣的結構指令:如何導出結構指令屬性以用於模板?

@Directive({ 
    // tslint:disable-next-line:directive-selector 
    selector: '[cycle]' 
}) 
export class CycleDirective { 
    private cycle$: any; 

    constructor(
    private tRef: TemplateRef<any>, 
    private vcRef: ViewContainerRef) { } 

    @Input() cycleInterval: number | Observable<any> = 1000; 
    @Input() set cycle(source: Array<any[]>) { 
    const interval$ = ofType(Number, this.cycleInterval) ? 
     Observable.timer(0, this.cycleInterval as number) : this.cycleInterval; 

    if (!hasProperty(interval$, 'subscribe')) { 
     throw new Error('Input interval must be Number or Observable'); 
    } 

    this.cycle$ = Observable.of(source) 
     .combineLatest(interval$ as Observable<any>) 
     .map(([items, index]) => items[cycle(index - 1, items.length)]) 
     .forEach(item => { 
     this.vcRef.clear(); 
     this.vcRef.createEmbeddedView(this.tRef); 
     }); 
    } 

} 

如何導出當前項目,指數(或任何東西),以便能夠在模板中使用它?

<div *cycle="['a', 'b', 'c']; interval: 2000"> 
    testing: <!-- current item --> 
</div> 

理想情況下,應該使用像ngFor

<div *cycle="let item of ['a', 'b', 'c']; interval: 2000">{{ item }}</div> 

回答

2

你可以試試:

this.vcRef.createEmbeddedView(this.tRef, { $implicit: item, index: index }); 

而且在模板:

*cycle="['a', 'b', 'c']; interval: 2000; let item; let i = index" 

您的需求:

directive.ts

@Directive({ 
    // tslint:disable-next-line:directive-selector 
    selector: '[cycle][cycleOf]' 
        ^^^^^^ but we can omit this 
}) 
export class CycleDirective { 
    private cycle$: any; 

    constructor(
    private tRef: TemplateRef<any>, 
    private vcRef: ViewContainerRef) { } 

    @Input() cycleInterval: number | Observable<any> = 1000; 
    @Input() set cycleOf(source: Array<any[]>) { 
        ^^^ required 
    ... 
     this.vcRef.createEmbeddedView(this.tRef, { $implicit: item, index: index }); 
    ... 
    } 

} 

父母template.html

<div *cycle="let item of ['a', 'b', 'c']; interval: 2000; let i = index"> 
    {{ item }} {{ i }} 
</div> 

也見

+0

謝謝,我會嘗試這個... – Sasxa

+0

完美的作品(: – Sasxa

+0

不客氣! – yurzui