最终目标是使用动态创建的嵌套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>
Run Code Online (Sandbox Code Playgroud)
在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]
Run Code Online (Sandbox Code Playgroud)
关于如何使这个工作的任何想法?
小智 36
只想添加一个适合我的替代方案(无需额外的管道):
*ngFor="#obj of (myAsyncObject | async)?.prop1?.prop2"
Run Code Online (Sandbox Code Playgroud)
好的,我自己设法解决了.只需创建一个自定义管道并传入参数.在我的情况下:
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]];
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后导入:
import {CustomPipe} from '../pipes/custompipe'
@Component({
selector: 'mypage',
templateUrl: '../templates/mytemplate.html',
pipes: [CustomPipe],
directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
})
Run Code Online (Sandbox Code Playgroud)
并使用:
*ngFor="#obj of myAsyncObject | async | customPipe:'prop1':'prop2'"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20436 次 |
| 最近记录: |