angular 2 *ngFor,当iterable还没有被实例化时

angular 2 *ngFor, when iterable hasn't be instantiated yet

我有几个 *ngFor 循环取决于可能尚未实例化的可迭代对象。 (例如,他们正在等待可观察的)

我可以在视图中使用这样的表达式吗?

更新: 这是抛出错误的部分

组件

activeLectureContent:LectureContent;

查看

  <div class="filter-units">
    <div>Units</div>
    <a (click)="setUnit(i)" class="btn btn-icon-only blue filter-unit-btn" *ngFor="#unit of activeLectureContent.content; #i = index">
      <span>{{i+1}}</span>
    </a>
  </div>

无法读取 [null]

中未定义的 属性 'content'

讲座内容是这样的

export class LectureContent{
  constructor(
    public name:string = '',
    public filter:LectureFilter[]=[],
    public show:boolean = true,
    public hover:boolean = false,
    public content:any[]=[]
  ){}
}

干杯

您可以使用 ngIf 指令,因此它仅在 iterable 是 thruthy 时呈现。

<div *ngIf="iterable" *ngFor="let item of iterable"><div>

您正在寻找 AsyncPipe:

<div *ngFor="#item of iterable | async"></div>

它适用于 Observables、Promises 和 EventEmitters。您可以在 guide (chapter "The impure AsyncPipe") and documentation.

中获得更多相关信息

如果它是 "simply" 一个可迭代的(数组,...但不可观察,承诺),我认为没有什么可做的。 ngFor 将检查可迭代对象的更新。当值变为not null时,ngFor会更新对应的内容:

查看此示例:

@Component({
  selector: 'app'
  template: `
    <div>
      <div *ngFor="#category of categories;#i=index">{{i}} - {{category.name}}</div>
    </div>
  `
})
export class App {
  constructor() {
    Observable.create((observer) => {
      setTimeout(() => {
        observer.next();
      }, 2000);
    }).subscribe(() => {
      this.categories = [
        { name: 'Cat1', value: 'cat1' },
        { name: 'Cat2', value: 'cat2' },
        { name: 'Cat3', value: 'cat3' },
        { name: 'Cat4', value: 'cat4' }
      ];
    });
  }
}

看到这个 plunkr:https://plnkr.co/edit/J1aVclVcjJPqm1Qx9j0j?p=preview

对于 beta 17,您需要将 # 替换为 let:

<div *ngFor="let category of categories;let i=index">{{i}} - (...)

ngIfngFor 似乎效果不佳。看到这个 plunkr:https://plnkr.co/edit/aE3umzzSZ5U9BocEE9l6?p=preview

如果 "iterable" 是一个 observable 或一个 promise,查询异步管道。

编辑

您可以尝试类似的方法:

<template [ngIf]=" activeLectureContent ">
    <a (click)="setUnit(i)" class="btn btn-icon-only blue filter-unit-btn" *ngFor="#unit of activeLectureContent.content; #i = index">
      <span>{{i+1}}</span>
    </a>
</template>

我使用 ngIf 的扩展语法,因为 ngFor 和 ngIf 不能用于同一元素。

恢复这个 post 因为我最近有同样的问题。

这是 Angular 的 (safe navigation operator) 的完美案例。

来自文档:

The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined values in property paths.

所以问题的示例视图是:

  <div class="filter-units">
    <div>Units</div>
    <a (click)="setUnit(i)" class="btn btn-icon-only blue filter-unit-btn" 
      *ngFor="let unit of activeLectureContent?.content; let i = index">
      <span>{{i+1}}</span>
    </a>
  </div>

添加 ?在 activeLectureContent 之后意味着如果 activeLectureContent 为空或未定义,ngFor 将被忽略。