angular 2 - how to set <select> default sele

2020-06-30 06:55发布

问题:

My template is like this

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

How can I set option AM selected by default?

回答1:

The old pure HTML way simply works with Angular2, if you do not want to do anything dynamically:

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

But the following is the Angular 2 way which allows you to dynamically assign selected value, which may be the practical and common use case: (You need to import FormsModule)

<select [(ngModel)]='selectedValue'>
  <option value='AM'>AM</option>
  <option value='PM'>PM</option>
</select>

and in your component class

selectedValue = 'AM'; // You may assign 'AM or 'PM' dynamically here

The following links may be useful:

https://angular.io/api/forms/NgSelectOption

https://angular.io/api/forms/NgModel

The above mentioned Angular 2 method is template driven forms method. There is another way of doing the same which is reactive forms approach described bellow: (You need to import ReactiveFormsModule)

<select [formControl]='control'>
  <option>AM</option>
  <option>PM</option>
  </select> 

and in your component class

control = new FormControl('AM');

The following link may be useful:

https://angular.io/api/forms/FormControlDirective



回答2:

<select [(ngModel)]="defaultValue">
  <option>AM</option>
  <option>PM</option>
</select>
export class MyComponent {
  defaultValue = 'PM';
}

Usually it's done like

<select [(ngModel)]="defaultValue">
  <option *ngFor="let value of values" [ngValue]="value">{{value}}</option>
</select>

export class MyComponent {
  values = ['AM', 'PM'];
  defaultValue = this.values[1];
}

Hint For non-string values use `[ngValue]="..."

<select [(ngModel)]="defaultValue">
  <option [ngValue]="values[0]">AM</option>
  <option [ngValue]="values[2]">PM</option>
</select>


回答3:

For a template driven form, I did this and got default selection.

<select [(ngModel)]="defaultOption" name="identification">
                <option [value]=null>Select</option>
                <option *ngFor="let option of identification" [value]="option.id"> {{ option.name }} </option>
              </select>

and in the component.ts file,

   identification = [
    { id: 1, name: 'Passport'},
    { id: 2, name: 'Adhaar'},
    { id: 3, name: 'Driver\'s license'},
    ];
    defaultOption = null;

On load, we could get Select as default selected.



回答4:

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



回答5:

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.



回答6:

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".



回答7:

My NgModel was assigned to an array and I couldnt set a default for each element in the array. By default the values are undefined so you can set your default option value with that.

export class MyComponent {
  someList:Array<any> = ['apples','banana','oranges'];
  myModel: Array<any> = [];
}


<div *ngFor="let list of someList; let i = index;">
  <select  [(ngModel)]="myModel[i]" class="form-control">
    <option [value]="undefined">DEFAULT</option>
    <option [value]="'a'">A</option>
    <option [value]="'b'">B</option>
  </select>
 </div>


回答8:

        <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.



回答9:

/** All includes */

@Component({
              selector: 'app-select',
              template: `

          <form [formGroup]="select_form">

              <select *ngFor="let item of select_options" 
               formControlName="select_control">
                 <option value=="-1">Select one option ... </option>
                 <option value="{{item.id}}">{{item.text}}</option>
              </select>

              <button type="button" (click)="setActive("-1")"></button>

          </form>
              `
})

    export class SelectComponent extends OnInit{
        private select_form: FormGroup;
            select_options: any[] = 
            [{id: 1, text: "Text 1", id: 2,  text: "Text 2"}];

        constructor(private builder: FormBuilder){

        }

        ngOnInit(){
          this.init();
        }

        init(){
          this.select_form= this.builder.group({
             select_control: new FormControl("1", [/** Validation */])
          });
        }

        setActive(active_value: string){
           this.select_form.get('select_control').patchValue(active_value);
        }
    }


回答10:

<select [(ngModel)]="selectedValue">
  <option value="selectOptions" disabled="disabled">---Select Options---</option>
  <option *ngFor="let somevalue of somevalues" [value]="somevalue">{{somevalue}}</option>
</select>

export class MyComponent {
  ngOnInit() {
   somevalues= ['abc', 'def','ghi'];
   selectedValue= "selectOptions";
  }
  someFunction() {
     // process selected option 
     var selection = selectedValue;
     :
     :
     //reset selectedValue to "--Select Options--"
     selectedValue = "selectOptions";
  }

}


回答11:

options = [
  {
    name : 'Option A',
    value : 1
  },
  {
    name : 'Option B',
    value : 2
  },
  {
    name : 'Option C',
    value : 3
  }
];
placeHolder = 'select option';

<div>
  <label>Label:</label>
  <select>

    <option [value]="null" ngValue="null" hidden>{{placeHolder}}</option>
    <option *ngFor="let option of options"
            [ngValue]="option.value">{{option.name]}}
    </option>
  </select>
</div>


回答12:

<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>


回答13:

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);
}


回答14:

this way:

<select [(ngModel)]="Value">
  <option disabled selected value="">AM</option>
  <option >PM</option>
</select>


标签: angular