angular 2 - how to set <select> default selected option

前端 未结 2 504
陌清茗
陌清茗 2021-02-12 08:23

My template is like this


How can I set optio

相关标签:
2条回答
  • 2021-02-12 09:03

    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

    0 讨论(0)
  • 2021-02-12 09:03
    <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>
    
    0 讨论(0)
提交回复
热议问题