Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using async pipe with ngFor

Tags:

angular

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>

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?

like image 210
TylerDurden Avatar asked Nov 17 '15 00:11

TylerDurden


2 Answers

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]];
        }
    }
}

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'"
like image 107
TylerDurden Avatar answered Sep 21 '22 00:09

TylerDurden


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

*ngFor="#obj of (myAsyncObject | async)?.prop1?.prop2"
like image 42
user1696255 Avatar answered Sep 23 '22 00:09

user1696255