Jay
Jay

Reputation: 339

Angular Material - md-select - selected item in dropdown

I have a md-select dropdown with list of user names. I want the lead.id to be selected. How can I achieve this?

  <md-select formControlName="lead" ng-model="plan.lead.id" id="lead" style="min-width: 200px;">
                    <md-option *ngFor="let lead of users" [value]="lead.id">
                        {{lead.displayName}}
                    </md-option>
                </md-select>

getLead() {
        this.service.getLead(this.id)
            .subscribe(res => {
                this.plan = res;
                console.log("lead: " + this.plan.lead);     
            }); 
    }

Upvotes: 3

Views: 1500

Answers (2)

AVJT82
AVJT82

Reputation: 73337

You are using ng-model, which is AngularJS syntax. But you are not needing to use ngModel here, since you have a reactive form (??), and you can set the formcontrol with the value you have received. So when you have received your plan, you can set the value:

this.myForm.get('lead').setValue(this.plan.lead.id)

Your template:

<md-select formControlName="lead" id="lead" style="min-width: 200px;">
  <md-option *ngFor="let lead of users" [value]="lead.id">
      {{lead.displayName}}
 </md-option>
</md-select>

Wait a couple of seconds and in the Plunker the value will be set.

Upvotes: 2

developer033
developer033

Reputation: 24864

First of all, are you using reactive forms?

If so, despite the fact that you're using an incorrect syntax in ng-model (it should be [(ngModel)]), you shouldn't use it with reactive forms.

Use only formControlName or [formControl].

Upvotes: 0

Related Questions