【问题标题】:How to export Structural Directive property for use in templates?如何导出结构指令属性以在模板中使用?
【发布时间】:2017-09-28 11:27:23
【问题描述】:

我有这个结构指令:

@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>

【问题讨论】:

    标签: angular angular-directive


    【解决方案1】:

    你可以试试:

    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 });
        ...
      }
    
    }
    

    父模板.html

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

    另见

    【讨论】:

    • 完美运行 (:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 2019-05-26
    • 2019-04-08
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多