简体   繁体   中英

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

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.

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] .

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