如何将 angular 模板中的枚举值作为输入传递?
How to pass enum value in angular template as an input?
我有一个将类型作为输入的子组件
子组件:
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 个局部变量并在模板中分配它们太多了。
对此有更好的解决方案吗?
要在模板中使用枚举,您只需将枚举直接分配给变量即可。
@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>
我有一个将类型作为输入的子组件
子组件:
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 个局部变量并在模板中分配它们太多了。
对此有更好的解决方案吗?
要在模板中使用枚举,您只需将枚举直接分配给变量即可。
@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>