angular 2 * ngFor,当iterable尚未实例化时

前端之家收集整理的这篇文章主要介绍了angular 2 * ngFor,当iterable尚未实例化时前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有几个* ngFor循环取决于可能尚未实例化的iterables. (例如,他们正在等待观察)

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

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

零件

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]中读取未定义的属性内容

讲座内容如下所示

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

干杯

解决方法

如果它“简单地”是一个可迭代的(数组,……但不是可观察的,承诺),我认为没有什么可做的. ngFor将检查iterable的更新.当值变为非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,您需要将#替换为:

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

似乎ngIf与ngFor的效果不佳.见thisp plunkr:https://plnkr.co/edit/aE3umzzSZ5U9BocEE9l6?p=preview

如果“iterable”是可观察的或承诺,则将异步管道排入队列.

编辑

你可以尝试这样的事情:

<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不能用于同一个元素.

猜你在找的Angularjs相关文章