简体   繁体   中英

How can I set default value of dropdown (select-option) input in Angular 2 reactive form

I have a dropdown list of objects. It's a person object that has a properties of id , firstName and lastName .

<select formControlName="person">
    <option *ngFor='let person of persons" [ngValue]="person">{{person.firstName+' '+person.lastName}}</option>
</select>

Let' say I have an object person which I want to check if this person object I have is in the dropdownlist. If exist I want that object person to be the selected option /default value of the dropdown list.

You can make use of the formControl and set the default value with that. Depending on if you have the value on initialization of the component, you can set the value when you build the form, otherwise use patchValue when you have received the value. So when you build the form (if you have the data)

ngOnInit() {
  this.myForm = this._fb.group({
    person: [this.persons[1]]
  }); 
}

Demo

PS, usually we do not use ngValue here, which binds the whole object, but of course this also works if you want/need to do it :)

Approach without using ngModel..You can also select default value of dropdown using index (i) of each iteration inside *ngFor . You can use 'selected' property on option element and then set the value of index (i) equivalent to which option you want to make default. Here I have made 2nd option to be by-Default selected. Index is the index of each option in an array. Below is the code modified a bit for the same:

@Component({ selector: 'my-app', template: ` {{option.name}}

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