如果我使用 *ngFor 构建访问链,我将无法访问异步管道提供的对象的属性。
在下面的示例中,假设测试行中的 Parking
和下面两行的 ?.[filter.propName]
表示同一对象上的同一键。测试线将评估为真,但选中的属性不会。为什么?在使用 *ngFor 将这些标记出来时如何访问属性?
例如,如果 {{(compModel | async)?.Parking?.Garage}} === true
我会期望 {{(compModel | async)?.[filter .propName].instance}} === true
同样,但事实并非如此。
以下语法无效。我用它来演示预期的功能。
<div *ngFor="let filter of filters | async">
...
<fieldset class="filter-category-title">
<legend>{{filter.name}}</legend>
<label *ngFor="let instance of filter.options">
test: {{(compModel | async)?.Parking.instance}}
<input type="checkbox"
checked={{(compModel | async)?.[filter.propName].instance}}
(click)="amenityEmit({category: filter.propName, filter: instance, resetCategory: false})">
{{instance}}
</label>
</fieldset>
</div>
我从服务器获取的过滤数据格式如下。我用它来构建一个比较模型,也在下面,这就是我管理搜索结果页面状态的方式。 ([key: string]
始终是过滤器中的 propName)。
export interface Filter {
base: boolean,
filter: string,
propName: string,
unionType: string,
inputType: string,
options: {
options: string[],
sectionTitle: string
}[] | string[]
}
compModel 接口(interface):
export interface CompModel {
[key: string]: {
touched: boolean
unionType: string,
options: {
options: string[],
sectionTitle: string
}[] | string[],
updateSelf(x: CompModel, y: Action): void
}
}
最佳答案
安全导航运算符 ?.
不适用于 []
。没有 ?[]
运算符,也没有 ?.[]
或 .[]
运算符,因此这是行不通的。
你可以试试
{{(compModel | async) && (compModel | async)[filter.propName].instance}} === true
否则你需要将一些代码移动到组件类
例如
this.compModel = someService.getSomeObservable()
.filter(val => !!val)
确保没有null
值
关于angular - 在带有 *ngFor 的 Angular 2 模板中使用可观察对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42057483/