angular 2 - how to set <select> default sele

2020-06-30 07:16发布

My template is like this

<select>
  <option>AM</option>
  <option>PM</option>
</select>

How can I set option AM selected by default?

标签: angular
14条回答
小情绪 Triste *
2楼-- · 2020-06-30 07:29

I noticed no one gave the non-ngModel solution, which is this:

html:

    <select (change)="valueSelected($event.target.value)">
        <option *ngFor="let option of options">{{option}}</option>
    </select>

typescript:

valueSelected(value:string) {
  console.log(value);
}
查看更多
Anthone
3楼-- · 2020-06-30 07:30

Should work, try this

<select>
  <option [selected]='a=="None"'>None</option>
  <option [selected]='a=="AM"'>AM</option>
  <option [selected]='a=="PM"'>PM</option>
</select>

//in .ts file
a='PM'

This method is more benefitial in case of while you are genrating your options using loop i.e *ngFor , you just have to add [selected] attribute and bind the value in your class

PS: this method is efficient in static as well as dynamic binding.

查看更多
看我几分像从前
4楼-- · 2020-06-30 07:31
        <select>
            <option [ngValue]="null">All</option>
            <option *ngFor="let oneItem of items" [ngValue]="oneItem.id">
               {{oneItem.description}}
            </option>
        </select>

Simply add option to the list. This has worked for me in Angular 4.

查看更多
【Aperson】
5楼-- · 2020-06-30 07:32

I don't know why so much long answers here.

Short Answer :

use [selected]="isSelected" in your option tag!

Solution :

<select>
  <option [selected]="isSelected">AM</option>
  <option>PM</option>
</select>

Source:

https://medium.com/@phismonster/set-default-value-for-select-in-angular-2-27f0da413935

Edit 1 : Example with array :

arr = [{str: 'A', isSelected: false},
{str: 'B', isSelected: true},
{str: 'C', isSelected: false},
{str: 'D', isSelected: false},
];

<select>
    <option *ngFor="let a of arr" value="a.str" [selected]="a.isSelected">{{a.str}}</option>
</select>

link with working example : https://stackblitz.com/edit/selected-test

查看更多
时光不老,我们不散
6楼-- · 2020-06-30 07:36
<select class="form-control" [(ngModel)]="someList.key" name="key" #key="ngModel" required>
     <option value="undefined" selected disabled>Select option</option>
     <option *ngFor="let data of someList" value="{{data.key}}">{{data.key}</option>
 </select>
查看更多
混吃等死
7楼-- · 2020-06-30 07:43

In Template file:

 <select name="AMPMTime" [(ngModel)]="aMPMTime.time" #aMPMTime="ngModel">
      <option [ngValue]="0">AM</option>
      <option [ngValue]="1">PM</option>
 </select>

In Component.ts file:

ngOnInit() {
    this.aMPMTime.time= 0;
}

And the select control will default select at "AM".

查看更多
登录 后发表回答