I have such enum/range:
period: 'UTD' | 'EOM' | 'ETM'
I want to iterate through all options in select:
<select
[value]="period"
(change)="period=$event.target.value"
>
<ng-container *ngFor="let e of period">
<option [value]="e" [selected]="e === period">
{{ e }}
</option>
</ng-container>
</select>
I need to get HTML with option per available enum in period range:
UTD EOM ETMHow is that possible please?
CodePudding user response:
Unions & string literals have no existence at runtime, therefor you can't iterate over them.
What you can do is : define your union like that
const Periods = [ 'UTD' ,'EOM', 'ETM'] as const;
type Period = typeof Periods[number];
And you will be able to iterate over Periods
CodePudding user response:
Thanks to Matthieu Riegler's answer, it works. I had a little pain to put working in component so here is a whole sample:
const Periods = ['UTD', 'EOM', 'ETM'] as const;
type Period = typeof Periods[number];
@Component({
selector: 'app-input-date',
templateUrl: './input-date.component.html',
styleUrls: ['./input-date.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class InputDateComponent implements OnInit, Validator, ControlValueAccessor {
period: Period;
periods = Periods;
...
and in HTML:
<select
[value]="period"
(change)="period=$event.target.value"
[disabled]="disabled"
>
<ng-container *ngFor="let e of periods">
<option [value]="e" [selected]="e === period">
{{