问题
I have two items in dropdown. I need to set initial value as first value from array below is my code
objects = ['production', 'development'];
this.object = this.objects[0];
<div class="item">
<select formControlName="db" class="form-control" (change)="changeDb($event)" [ngModel]="object">
<option *ngFor="let object of objects" [ngValue]="object">{{object}}</option>
</select>
</div>
The value is not setting using above code.It is showing in ng reflect model but not in UI
回答1:
You can add an "if" statement if your default object is equal to the object in your array then add selected attribute in your element. Also change your variable name to maybe "defaultObject" to not conflict in your "for of" statement.
objects = ['production', 'development'];
this.defaultObject = this.objects[0];
<div class="item">
<select formControlName="db" class="form-control" (change)="changeDb($event)" [ngModel]="object">
<option *ngFor="let object of objects" [ngValue]="object" [selected]="defaultObject == object">{{object}}.
</option>
</select>
</div>
回答2:
You can cleanly achieve this by using the ngModel binding like so:
component.ts
export class AppComponent {
objects = ['production', 'development'];
// The selected node of the objects array
selected = this.objects[1];
}
component.html
<div class="item">
<select class="form-control" (change)="changeDb($event)" [ngModel]="selected">
<option *ngFor="let object of objects">{{object}}</option>
</select>
</div>
The above code as it is would preselect the 'development' node of the objects array.
So in your case to preselect the first option, you would change:
selected = this.objects[1];
to:
selected = this.objects[0];
Example Stackblitz: https://stackblitz.com/edit/angular-esulus
来源:https://stackoverflow.com/questions/64064480/how-to-set-initial-value-in-dropdown-in-angular8