2015-11-17 2 views
12

最終的な目標は、動的に作成されたネストされたngForを使用することです。 私は以前のものに応じて、一連のドロップダウンメニューを作成しようとしています。ドロップダウンメニューの正確な数は不明であり、動的に作成されます。例:Angular2の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]  

任意のアイデア?

答えて

9

OK、自分で解決することができます。単にカスタムパイプを作成し、中にパラメータを渡す私の場合:。

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

はちょうどその選択肢を追加したいです私のために働いた(余分なパイプは不要):

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

多分私はそれを逃したことがありますが、何がありますか?フラグは?それはオプションか何かになるように思える? – markthethomas

+0

angular2の安全なナビゲーション演算子を検索できます。 https://angular.io/docs/ts/latest/guide/template-syntax.html#!#safe-navigation-operator角度安全ナビゲーションオペレータ(?)は、より安全で便利な方法で、プロパティパス。この式は、最初のヌル値に当たったときに退く。表示は空白ですが、アプリはエラーなく回転し続けます。 – sathishvj

関連する問題