Angular Material - md-select - selected item in dropdown

I have an md-select dropdown menu with a list of usernames. I want 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);     
            }); 
    }

      

+3


source to share


2 answers


You are using ng-model

, which is AngularJS syntax. But here, you don't need to use ngModel, since you have a reactive form (??) and you can set the formcontrol with the value you got. So when you got yours 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 Plunker will be set to.

+2


source


First, are you using reactive forms?

If so, even though you are using the wrong syntax in ng-model

(it should be [(ngModel)]

), you should not use it with reactive forms.



Use only formControlName

or [formControl]

.

0


source







All Articles