简体   繁体   中英

Angular 5 Set selected value of HTML Select Element

Here is what I'm trying to do:

 <select name="manager" id="manager" [(ngModel)]="property.manager" class="form-control" (change)="onChangeManager($event)" required> <option disabled value="">Select Manager</option> <option *ngFor="let manager of managers" [ngValue]="manager" [selected]="manager?.name === 'Subhan Ahmed'"> {{manager?.name}} </option> </select> 

What I need is when the view is initialised, I need to set the value of the select where manager?.name == property.manager.name (which is loaded from db on on another event). I've tried to place a default text Subhan Ahmed to select the default value but its not working.

Managers are loaded at the start, I load them from Firestore and assign them to a variable managers: Observable<Manager>; during subscribe() , while property.manager is loaded after another input's change event.

Am i missing something?

You can select an item of the dropdown list by setting the value of property.manager . Assuming that selectedName is the name of the Manager item that you want to select, you can do this:

// Case sensitive
this.property.manager = this.managers.find(m => m.name === this.selectedName);

// Case insensitive
let selectedNameUp = this.selectedName.toUpperCase();
this.property.manager = this.managers.find(m => m.name.toUpperCase() === selectedNameUp);

Here are the relevant parts of the markup and code. See this stackblitz for a demo.

HTML:

<select name="manager" [(ngModel)]="property.manager" class="form-control" required>
  <option disabled [ngValue]="undefined">Select Manager</option>
  <option *ngFor="let manager of managers" [ngValue]="manager">{{manager.name}}</option>
</select>
<input type="text" [(ngModel)]="selectedName" (ngModelChange)="onNameChange($event)">

Code:

selectedName: string;

property = {
  ref_no: '',
  address: '',
  manager: undefined
};

managers = [
  { "company": "Test Company", "name": "John Doe", "id": "3oE37Fo2QxGHw52W7UHI" }, 
  { "company": "Another Company", "name": "John Brown", "id": "LRF8xAi48rRuWu0KZex3" }, 
  { "company": "XYZ", "name": "Subhan Ahmed", "id": "TqOQHbdwJdwgwD8Oej8v" }
];

onNameChange($event) {
  let selectedNameUp = this.selectedName.toUpperCase();
  this.property.manager = this.managers.find(m => m.name.toUpperCase() === selectedNameUp);
}

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