Reputation: 1810
Interestingly, I do not seam to find a simple solution for a simple requirement of having list of select options open / dropped down on page load.
I am working with Angular 8 in case that offers some simple script, but I was assuming HTML/CSS should have this built in with some property - such as: 'isOpen' or 'isDroppedDown' ...
I see some are resolving it with 'size' or 'multiple', but these change the visual property of the control and I want consistency. The control needs to be/look the same (with the little arrow ...)
Code example: Say we have this list/array in TS/Angular code:
philosophers = ['Aristotle', 'Epicurus', 'Descartes', 'Seneca', 'Plato'];
and we feed it to this template:
<select name="phil_selector" [(ngModel)]="selected_phil">
<option *ngFor="let item of philosophers; index as ix" [value]="ix">
{{item}}
</option>
</select>
// For those who prefer plain HTML:
<select name="phil_selector">
<option value="0"></option>
<option value="1">Aristotle</option>
<option value="2">Epicurus</option>
<option value="3">Descartes</option>
<option value="4">Seneca</option>
<option value="5">Plato</option>
</select>
We do not want any item/philosopher be selected by default, but when the page loads, we want the drop-box be already open, to make it clear to the user, that 1st thing he has to do, is to make his selection from the visible list of options. So he will see this:
And, he just clicks on his choice and goes on ...
To summarize the requirement - we need to have a list of 'select' options open (dropped down) after HTML page has loaded.
Upvotes: 0
Views: 1050
Reputation: 3286
If you are willing to use mat-select of Angular Material you can do it like this:
import {Component, ViewChild, AfterViewInit} from '@angular/core';
/**
* @title Basic select
*/
@Component({
selector: 'select-overview-example',
templateUrl: 'select-overview-example.html',
styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample implements AfterViewInit {
@ViewChild('mySelect') mySelect;
foods = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'}
];
ngAfterViewInit() {
this.mySelect.open();
}
}
/** Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license */
<mat-form-field>
<mat-select #mySelect placeholder="Favorite food">
<mat-option *ngFor="let food of foods" [value]="food.value">
{{ food.viewValue }}
</mat-option>
</mat-select>
</mat-form-field>
<br>
<button (click)="click()">click</button>
<!-- Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license -->
Or you can try Jquery options like shown here How to open select programmatically
Upvotes: 1