1

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.

2 Answers 2

2

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 :)

Sign up to request clarification or add additional context in comments.

5 Comments

I already tried it before I posted a question here @AJT_82. It selects the person. But not updating in the view :(
"it selects the person but not updating the view" what does that mean exactly?
I print the formcontrols value using <p>{{personForm | json</p> so I can see if the form value changes and to see if the person is selected. But in the actual view in the dropdown list it selects nothing.
Well, I made a plunker for you, could you fork it and recreate the issue and I'd be happy to take a look :)
Hi @AJT_82 can I message you outside stackoverflow? I want to ask more questions. I've been trying to solve this one for two days now but I was still not able to solve it.
0

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}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.