Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

Default value select option angular

im new to Angular. And im having issues with selects and default options. I have an array of car brands that are being displayed with an ngFor in the option tag and i have "Seleccione una marca" which will be the default option. Here is the code.

<div class="form-group float-label-control" [ngClass]="{ 'has-error': formStep2.submitted && !brand.valid }">
    <label for="brand" title="Este campo es obligatorio">Marca*</label>
    <select class="form-control" name="brand" id="brand" [(ngModel)]="stepTwo.brand" #brand="ngModel" (change)="getModels(stepTwo.brand)" required>
      <option value="">Seleccione una marca</option>
      <option *ngFor="let brand of brands" [ngValue]="brand">{{ brand.descripcion }}</option>
     </select>
   <div *ngIf="formStep2.submitted && !brand.valid" class="help-block text-danger">Campo requerido</div>
</div>

The issue is that by default the option is blank, and when clicked it contains "Seleccione una marca" and all the brand array. Is not making "Seleccione una marca " the default option. Thanks in advance for your time.

EDIT I manage to solve it. By initializing the ngModel property with the value of the option i like to use as default. In this case i did something like this.

this.stepTwo.brand = "";

And whoala the problem was solved.

question from:https://stackoverflow.com/questions/65920071/default-value-select-option-angular

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This will help you to set default value for select:

<select [(ngModel)]="selectedOption"></select>

And add in class:

export class AppComponent {
  selectedOption = 'Seleccione una marca';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...