Ilan Finkel
Ilan Finkel

Reputation: 496

Angular2 Material - can't set selected option to md-select

I'm trying to create an edit form for a client object, first, I'm getting the data from a service and then init the form

ngOnInit(){

    this.clientService.getCountries().subscribe(
        (result:any) => {
            this.countries = result.countries;
        }
    );

    this.subscription_route = this.route.params.subscribe(
        (params: any) =>{
            if(params.hasOwnProperty('id')){
                this.client_guid = params['id'];
                this.subscription_service = this.clientService.getClient(this.client_guid).subscribe(
                    (result:any) => {
                    this.client = result.client;
                        this.initForm();
                }
              );
            }
        }
    );

  }

my initForm looks like this:

private initForm(){
        this.selectedOption = this.client.country_id;
    this.clientForm = this.formBuilder.group({
            name:[this.client.name,Validators.required],
            email:[this.client.email],
            vat_number:[this.client.vat_number],
            payment_terms_id:[this.client.payment_terms_id],
            address:[this.client.address],
            city:[this.client.city],
            postal:[this.client.postal],
            country_id:[this.client.country_id],
            accounting_key:[this.client.accounting_key],
            payment_amount:[this.client.payment_amount]
        });
  }

and then in my HTML template, I have this md-select

<md-select placeholder="country" formControlName="country_id">
    <md-option *ngFor="let country of countries" [value]="country.id">{{ country.name }}</md-option>
</md-select>

enter image description here

I'm not able to set the selected option that I getting from the server

Upvotes: 0

Views: 1976

Answers (2)

ChrisEenberg
ChrisEenberg

Reputation: 783

If you are using complex forms you can do something like

<md-select placeholder="country" [formControl]="clientForm.controls['country_id']">
    <md-option *ngFor="let country of countries" [value]="country.id">{{ country.name }}</md-option>
</md-select>

This will work, if you update the form value like

clientForm.controls['country_id'].setValue(2);

for instance.

Hope this helps.

Kind regards Chris

Upvotes: 0

Ilan Finkel
Ilan Finkel

Reputation: 496

I search everywhere and didn't find any answer, so I tried to play with the attributes and properties. I noticed that when I'm not using the *ngFor the selected option is selected, so I think that the problem was with the [value] property this way works for me:

<md-select placeholder="country" [(ngModel)]="selectedOption" formControlName="country_id">
    <md-option *ngFor="let country of countries" value="{{country.id}}">{{ country.name }}</md-option>
</md-select>

Upvotes: 1

Related Questions