简体   繁体   中英

How set selected default in Angular + 2

Created an object with the value 'true' in 'dropOptions'. In HTML I called [selected] = "option.selected" to include the selection.

The intention is to include the selected = "selected" element in the object with the value 'true'.

Thanks for help!

 dropOptions = [ { name: "ID parceiro", value: 'partner', selected: true }, { name: "ID", value: 'id' }, { name: "Nome do Item", value: 'name' } ];
 <select (change)="selectOption($event)" [(ngModel)]="selectedOption" class="form-control gray-txt"> <option [value]="option.value" [selected]="option.selected" *ngFor="let option of dropOptions">{{option.name}}</option> </select>

Try:

      <select (change)="selectOption($event)" [(ngModel)]="selectedOption"
        class="form-control gray-txt">
        <option [value]="option.value" [selected]="option.value === selectedOption" *ngFor="let option of dropOptions">{{option.name}}</option>
      </select>

if you want to set default value other than dropOptions array like placeholder then do like this.

component.html

 <select (change)="selectOption($event)" [(ngModel)]="selectedOption"
                class="form-control gray-txt">
                <option value="Select">Select</option>
                <option [value]="option.value" [selected]="option.selected" *ngFor="let option of dropOptions">{{option.name}}</option>
              </select>

component.ts

  selectedOption = 'Select';

And if you want set default from dropOptions array then try like this component.ts

 selectedOption = 'idB2W';

this will set second item selected because we have set option value as [value]="option.value" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM