Angular:ngIf 无法识别枚举类型

bin*_*Int 2 html css angular

*ngIf

<div *ngIf="type === FilterType.DateRangeFilter">
    ...
</div>
Run Code Online (Sandbox Code Playgroud)

结果出现错误

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 {

  }

}
Run Code Online (Sandbox Code Playgroud)

从这里:

export enum FilterType {
  DateRangeFilter, SensorSelectFilter
}
Run Code Online (Sandbox Code Playgroud)

有什么想法为什么这行不通吗?

小智 5

您的 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

}
Run Code Online (Sandbox Code Playgroud)

然后在你的模板中

<div *ngIf="type === filterType.DateRangeFilter">
    ...
</div>
Run Code Online (Sandbox Code Playgroud)