Danilo Körber
Danilo Körber

Reputation: 910

Define the selected option in a select after loading

I have the following scenario:

variable timezones

["Africa/Abidjan", "Africa/Accra", "Africa/Algiers", "Africa/Bissau", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/El_Aaiun", "Africa/Johannesburg", "Africa/Juba", "Africa/Khartoum", "Africa/Lagos", "Africa/Maputo", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Araguaina", "America/Argentina/Buenos_Aires", ....... ]

(shortened version)

component.html

<select>
    <option value="0">GMT/UTC</option>
    <option *ngFor="let tz of timezones" [value]="tz">{{tz}}</option>
</select>

compontent.ts

const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;

In my case, tzid is Europe/Berlin. How can I define this value as my selected option?

Upvotes: 0

Views: 15

Answers (1)

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31283

As you are using template driven forms, the first step is to define a variable to hold the value in ts file, for example, selectedTimezone and initialize it to the correct value :

selectedTimezone = 'Africa/Tripoli';

Then, in the template, use [(ngModel)] on the <select> tag :

<select [(ngModel)]="selectedTimezone">
  <option *ngFor="let tz of timezones" [value]="tz">{{tz}}</option>
</select>

Here is a stackblitz showing how it works with both template driven forms and reactive forms.

Upvotes: 1

Related Questions