将异步管道与 ngFor 结合使用

Using async pipe with ngFor

最终目标是使用动态创建的嵌套 ngFor。 我尝试创建一系列下拉菜单,每个都取决于前一个。下拉菜单的确切数量是未知的并且是动态创建的。示例:

<form [ngFormModel]="dropDownForm" (ngSubmit)="onSubmit()">
    <div *ngFor="#nr of numberOfDropdowns">
      <label>{{nr.name}}</label>
      <select [ngFormControl]="dropDownForm.controls[i]">
          <option  *ngFor="#item of Dropdown[nr.id] | async" value="{{item.value}}">{{item.name}}</option>
      </select>
    </div>
  <button type="submit">Submit</button>
</form>

整个过程在 Dropdown[nr.id] 处失败,这似乎不适用于异步管道。 我玩了一下:

{{myAsyncObject | async}} //works
{{myAsyncObject['prop1'] | async}} //fails silently
{{myAsyncObject['prop1']['prop2'] | async}} // EXCEPTION: TypeError: Cannot read property 'prop2' of undefined in [null]    

关于如何让它工作有什么想法吗?

好的,自己解决了。只需创建一个自定义管道并传入参数即可。在我的例子中:

import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({
    name: 'customPipe'
})
export class CustomPipe implements PipeTransform {
    transform(obj: any, args: Array<string>) {
        if(obj) {
            return obj[args[0]][args[1]];
        }
    }
}

然后导入:

import {CustomPipe} from '../pipes/custompipe'
@Component({
    selector: 'mypage',
    templateUrl: '../templates/mytemplate.html',
    pipes: [CustomPipe],
    directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
})

并使用:

*ngFor="#obj of myAsyncObject | async | customPipe:'prop1':'prop2'"

只想添加一个适合我的替代方案(不需要额外的管道):

*ngFor="#obj of (myAsyncObject | async)?.prop1?.prop2"