Select default option value from typescript angular 6

前端 未结 14 1561
轻奢々
轻奢々 2020-12-09 07:30

I have a select html like this:


                        
    
提交评论

  • 2020-12-09 07:59

    app.component.html

    <select [(ngModel)]='nrSelect' class='form-control'>
      <option value='47'>47</option>
      <option value='46'>46</option>
      <option value='45'>45</option>
    </select>
    

    app.component.ts

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      nrSelect = 47
    }
    
    0 讨论(0)
  • 2020-12-09 08:00
    <select class="form-control" [value]="defaultSelectedCurrency" formControlName="currency">
    <option *ngFor="let item of currency" [value]="item.value" [selected]="item.isSelected">{{item.key}}</option>
    </select>
    
    currency = [
        { key: 'USD', value: 'USD', isSelected: true },
        { key: 'AUD', value: 'AUD', isSelected: false }
      ];
      defaultSelectedCurrency: string;
    
     ngOnInit() {
        this.defaultSelectedCurrency = this.currency[0].value;
    }
    
    0 讨论(0)
  • 2020-12-09 08:02

    I think the best way to do it to bind it with ngModel.

    <select name="num" [(ngModel)]="number">
                    <option *ngFor="let n of numbers" [value]="n">{{n}}</option>
                  </select>
    

    and in ts file add

    number=47;
    numbers=[45,46,47]
    
    0 讨论(0)
  • 2020-12-09 08:04

    In addition to what mentioned before, you can use [attr.selected] directive to select a specific option, as follows:

    <select>
        <option *ngFor="let program of programs" [attr.selected]="(member.programID == program.id)">
            {{ program.name }}
        </option>
    </select>
    
    0 讨论(0)
  • 2020-12-09 08:07

    HTML

    <select class='form-control'>
        <option *ngFor="let option of options"
        [selected]="option === nrSelect"
        [value]="option">
            {{ option }}
        </option>
    </select>
    

    Typescript

    nrSelect = 47;
    options = [41, 42, 47, 48];
    
    0 讨论(0)
  • 提交回复
    热议问题