Problems using async pipe with ngFor in Angular2

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

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:

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?

回答1:

Just want to add an alternative that worked for me (no extra pipe necessary):

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


回答2:

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) {         if(obj) {             return obj[args[0]][args[1]];         }     } } 

Then import:

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

and use:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!