【问题标题】:Changing ngForOf to get Iterable from Behaviour Subject更改 ngForOf 以从 Behavior Subject 获取 Iterable
【发布时间】:2018-11-09 07:52:34
【问题描述】:

对于我的应用程序,我想要一个类似 ngForOf (https://github.com/angular/angular/blob/master/packages/common/src/directives/ng_for_of.ts) 的指令,但我不想从 Input() 中获取可迭代对象,而是从指令类中的行为主题中获取。

在 Host 类中使用 Behavior Subject 如下:

BehaviourSubject.subscribe((value) => {this.items = value})

<comp ngFor="let item of item"></comp>

不是一个选项。相反,我想在指令中开始订阅。

我想像这样使用指令:

 <comp *ngFor></comp>

有什么想法可以完成这项工作吗? (来自 ngForCode 的更改)

【问题讨论】:

    标签: angular directive angular2-directives


    【解决方案1】:

    未经测试,但给你一个想法:

    @Directive({
      selector: '[forBs]'
    })
    export class ForBs<T> extends NgForOf<T> {
    
      @Input()
      forBs: BehaviorSubject<NgIterable<T>> = new BehaviorSubject([]);
    
      get ngForOf(): NgIterable<T> {
        return this.forBs.getValue();
      }
    
      constructor(_viewContainer: ViewContainerRef, _template: TemplateRef<NgForOfContext<T>>, _differs: IterableDiffers) {
        super(_viewContainer, _template, _differs);
      }
    }
    

    这可能没有模板和 trackBy 支持.. 可能还有 onChangesdoCheck 挂钩的其他问题。但是话又说回来,这将帮助您走上正轨。

    用法如下:

    <comp *forBs="item$"></comp>
    

    在哪里

    item$ = new BehaviourSubject([]);
    

    不过话说回来,您也可以只使用async 管道;)

    <comp *ngFor="let item of item$ | async"></comp>
    

    【讨论】:

    • 你好。感谢您的回答,但仍在使用@Input()。用法应该是
    • @dindunuffin 不应该,因为你在它前面使用了*。如果查看*ngFor的源码,还可以看到@Input在ngForOf
    • 你想要*forBs="items$"
    • 我想要 并且喜欢 constructor(....){ BehaviourSubject.subscribe((value) => this.myIterableObejct=value) }
    • 但是如何才能将主题传递给指令呢?你需要一些绑定
    猜你喜欢
    • 1970-01-01
    • 2019-07-26
    • 2016-09-22
    • 2016-09-01
    • 1970-01-01
    • 2020-07-02
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多