在ngFor中使用异步管道 [英] Using async pipe with ngFor

查看:95
本文介绍了在ngFor中使用异步管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Ultimate goal is to use nested ngFor's created dynamically. I try to create a series of drop-down menus, each depending on the previous one. The exact number of drop-down menus is unknown and created dynamically. Example:

<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]失败,这似乎不适用于异步管道. 我玩了一下:

The whole things fails at Dropdown[nr.id] which does not seem to work with async pipe. I played around a bit:

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

关于如何使它工作的任何想法?

Any ideas on how to get this working?

推荐答案

好,我自己解决了这个问题.只需创建一个自定义管道并传入参数即可.

OK, managed to solve it myself. Simply create a custom pipe and pass the parameters in. In my case:

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中使用异步管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆