【问题标题】:How to pass enum value in angular template as an input?如何将角度模板中的枚举值作为输入传递?
【发布时间】:2021-10-13 04:54:32
【问题描述】:

我有一个将类型作为输入的子组件
子组件:

export enum PersonTypes {
  MALE = 'male',
  FEMALE = 'female'
}
@Component({
  selector: 'app-child'
})
export class ChildComponent {

  @Input() type: PersonTypes;
}

父组件:

@Component({
  selector: 'app-parent'
})
export class ParentComponent {

}

在父组件视图模板中:

 <div>
     <app-child [type]="PersonTypes.MALE"></app-child>
     <app-child [type]="PersonTypes.FEMALE"></app-child>
 </div>

那么,问题是如何在模板中传递不同的枚举值? 我找到了一个答案,说我们需要在父组件中创建一个新变量,然后将该值分配给模板中的“类型”,如下所示。

@Component({
  selector: 'app-parent',
  template:` <div>
     <app-child [type]="malePerson"></app-child>
     <app-child [type]="femalePerson"></app-child>
 </div>  `
})
export class ParentComponent {
        malePerson = PersonTypes.MALE;
        femalePerson = PersonTypes.FEMALE;
    }

对我来说这是一个过度的解决方案,如果我们有 10 个枚举属性,我们最终会创建 10 个局部变量并在模板中分配它们太多了。

有什么更好的解决方案吗?

【问题讨论】:

    标签: angular typescript enums angular-template


    【解决方案1】:

    要在模板中使用 Enum,您只需将 Enum 直接分配给一个变量。

    @Component({
      selector: 'app-parent'
    })
    export class ParentComponent {
    public PersonTypesEnum = PersonTypes; // direct reference 
    }
    

    现在 PersonTypesEnum 可以在模板中使用

    <div>
         <app-child [type]="PersonTypesEnum.MALE"></app-child>
         <app-child [type]="PersonTypesEnum.FEMALE"></app-child>
     </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多