通过 *ngFor 在 Angular 2 模板中使用可观察量

2024-01-04

如果我使用 *ngFor 构建访问链,我将无法访问异步管道提供的对象的属性。

在下面的示例中,假设Parking在测试线和?.[filter.propName]下面的两条线代表同一对象上的相同键。测试行的计算结果将为 true,但检查的属性不会。为什么?当使用 *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[]
}

补偿模型接口:

export interface CompModel {
  [key: string]: {
    touched: boolean
    unionType: string,
    options: {
      options: string[],
      sectionTitle: string
    }[] | string[],
    updateSelf(x: CompModel, y: Action): void
  }
}

安全航行运营商?.不适用于[]。没有?[]运算符,也没有?.[] or .[]运算符,因此这是行不通的。

你可以试试

{{(compModel | async) && (compModel | async)[filter.propName].instance}} === true

否则你需要将一些代码移动到组件类中

例如

this.compModel = someService.getSomeObservable()
.filter(val => !!val)

以确保没有null values

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 *ngFor 在 Angular 2 模板中使用可观察量 的相关文章

随机推荐