【问题标题】:Using async pipe with ngFor在 ngFor 中使用异步管道
【发布时间】:2016-02-18 05:47:40
【问题描述】:

最终目标是使用动态创建的嵌套 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]    

关于如何让它发挥作用的任何想法?

【问题讨论】:

    标签: angular


    【解决方案1】:

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

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

    【讨论】:

    • 也许我以前错过了它,但是 ?国旗呢?似乎它会使它成为可选的或其他什么?
    • 可以在angular2中查找安全导航算子。 angular.io/docs/ts/latest/guide/… Angular 安全导航运算符 (?.) 是一种更流畅、更方便的方法来防止属性路径中出现空值。表达式在遇到第一个空值时退出。显示为空白,但应用程序继续滚动而没有错误。
    【解决方案2】:

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

    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'"
    

    【讨论】:

      猜你喜欢
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2020-01-15
      • 2018-02-03
      • 2018-04-18
      • 2019-08-31
      • 1970-01-01
      相关资源
      最近更新 更多