I have a child component which takes type as an input
child component :
export enum PersonTypes {
MALE = 'male',
FEMALE = 'female'
}
@Component({
selector: 'app-child'
})
export class ChildComponent {
@Input() type: PersonTypes;
}
Parent component:
@Component({
selector: 'app-parent'
})
export class ParentComponent {
}
In the Parent component View template:
<div>
<app-child [type]="PersonTypes.MALE"></app-child>
<app-child [type]="PersonTypes.FEMALE"></app-child>
</div>
so , the question is how to pass the different enum values in the template ? i found one answer saying we need create a new variable in parent component and then assign that value to "type" in the template like below.
@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;
}
for me it is over killed solution , what if we have 10 enum properties , we end up creating 10 local variables and assigning them in the template is too much.
any better solution for this ?
CodePudding user response:
To use Enum in the template you just have to directly assign the Enum to a variable.
@Component({
selector: 'app-parent'
})
export class ParentComponent {
public PersonTypesEnum = PersonTypes; // direct reference
}
Now PersonTypesEnum can be used in a template
<div>
<app-child [type]="PersonTypesEnum.MALE"></app-child>
<app-child [type]="PersonTypesEnum.FEMALE"></app-child>
</div>