【问题标题】:Angular: ngIf doesn't recognize enum typeAngular:ngIf 无法识别枚举类型
【发布时间】:2021-10-24 01:10:02
【问题描述】:

这个*ngIf:

<div *ngIf="type === FilterType.DateRangeFilter">
    ...
</div>

导致错误

error TS2339: Property 'FilterType' does not exist on type 'FilterComponent

即使枚举类型FilterType 被导入到组件中:

import { FilterType } from '../filter-collection/filter-collection.component'

@Component({
  selector: 'app-filter',
  templateUrl: './filter.component.html',
  styleUrls: ['./filter.component.css']
})
export class FilterComponent {

  constructor(private type : FilterType) {
  }

  ngOnInit(): void {

  }

}

从这里:

export enum FilterType {
  DateRangeFilter, SensorSelectFilter
}

任何想法为什么这不起作用?

【问题讨论】:

标签: html css angular


【解决方案1】:

您的 HTML 模板无法访问在组件外部声明的变量。要解决此问题,请将枚举分配给组件范围内的变量

import { FilterType } from '../filter-collection/filter-collection.component'

@Component({
  selector: 'app-filter',
  templateUrl: './filter.component.html',
  styleUrls: ['./filter.component.css']
})
export class FilterComponent {

  constructor(private type : FilterType) {
  }

  ngOnInit(): void {

  }
  
  filterType = FilterType

}

然后在你的模板中

<div *ngIf="type === filterType.DateRangeFilter">
    ...
</div>

【讨论】:

    【解决方案2】:

    type 属性在FilterComponent 中用作private,以便能够使用它,将其更改为公共或在FilterComponent 中创建一个新属性并从构造函数中分配它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 1970-01-01
      • 2017-05-22
      • 2020-03-03
      • 2013-09-19
      • 2017-05-18
      相关资源
      最近更新 更多