【问题标题】:How to use ngswitch with enum in template?如何在模板中使用带有枚举的ngswitch?
【发布时间】:2021-06-23 14:34:55
【问题描述】:

我正在尝试使用枚举值更改模板。
TS:

enum NumType {
  first, second, third
}

@Component({
  selector: 'app-test',
  template: `
      <div [ngSwitch]="numType">
        <a *ngSwitchCase="numType.first" href="first">first</a>
        <a *ngSwitchCase="numType.second" href="second">second</a>
        <a *ngSwitchCase="numType.third" href="third">third</a>
      </div>
  `,
})
export class TestElementComponent {
  @Input() readonly numType: NumType;
}

HTML:

<app-test
[numType]="numType.first"
></app-info-element>  

然后我得到了这个错误:

ERROR TypeError: Cannot read property 'first' of undefined

你能告诉我需要做什么才能让它工作吗?
使用 Angular 8。

【问题讨论】:

    标签: angular enums ng-switch


    【解决方案1】:

    在 .html 中只能使用 属于 组件的变量。因此,如果您使用枚举,则应该在组件中使用变量。这就是您通常使用带有定义的 .ts 的原因

    //definitions.ts
    export enum NumType { //<---see the word "export"
      first, second, third
    }
    

    你的主要组件

       import {NumType} from './definitions'
       numType=NumType
    
       //now you can use
       <app-test [type]="numType.first"></app-test>  
    

    您的应用测试还应导入“NumType”

       import {NumType} from './definitions'
    
       numType=NumType
       @Input() type:NumType  //<--the input has no possible called "numType"
    
       //now you can use -see that the "switch" is about "type"
       <div [ngSwitch]="type">
            <a *ngSwitchCase="numType.first" href="first">first</a>
            <a *ngSwitchCase="numType.second" href="second">second</a>
            <a *ngSwitchCase="numType.third" href="third">third</a>
       </div>
    

    stackblitz

    顺便说一句,您使用的是 &lt;a href&gt;,如果您想使用 Angular,您应该使用

     <a routerLink="....">
    

    docs

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-11
      • 2016-06-20
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 2016-12-05
      相关资源
      最近更新 更多