[Fixed] How to default select the first item in multiple select field in Angular

Issue

I have made a stackblitz application where i am using a select box , with multiple selection . I want to default select the first item always , but i am unable to achieve it .

I am using selected = "i==0" but that doesnt help .

<select multiple class="custom-select" formControlName="cityName">
              <option *ngFor="let city of City ;let i= index;" [ngValue]="city" [selected]="i==0" (change)="changeCity($event)">{{city}}</option>
            </select>

Here’s the stackblitz link –

https://stackblitz.com/edit/angular-multi-select-dropdown-reactive-forms?file=src%2Fapp%2Fapp.component.html

Can anyone please help me on this ?

Solution

You can try this :

registrationForm = this.fb.group({
    cityName: [[this.City[0]], [Validators.required]]
});

The select is multiple, so in order to pre-select some options, you need to set the form value with an array. In this array, you just push the first city: this.City[0]

If you’re getting datas from a service, then you could do like this :

registrationForm: FormGroup;
cities = City[] = [];

constructor(private myService: MyService) {
  registrationForm = this.fb.group({
    cityName: [[], [Validators.required]]
  });

  this.myService.getCities().subscribe(cities => {
    this.cities = cities;
    this.registrationForm.get('cityName').patchValue([].concat(cities[0]))
  });
}

In this example, getCities() must return an Observable<City[]> like an Http request, or something like of(['Florida', 'South Dakota', 'Tennessee', 'Michigan', 'New York'])

Leave a Reply

(*) Required, Your email will not be published