Search code examples
angularangular-materialangular-ngmodelmd-select

Cannot set default value for md-select in angular 2


I am not able to set value for md-select in angular 2. I am populating the select list from constructor like:

 constructor() {
      this.testService.getTypes()
        .subscribe(result => {
            if (result.code === 200) { 
                this.types = result.data;                        
            }
        }, error => {
            this.router.navigate(['signin']);
        });
}

which works fine and data is populated correctly on the md-select. Then I am setting the value on ngOnInit() after running some query and sets the value like:

this.selectedValue = 'value';

I can access this value in html correctly using {{selectedValue}}. But the value is not loaded on the select field. md-select code is:

<md-select placeholder="Type" [(ngModel)]="selectedValue"  [formControl]="form.controls['typeName']"  [required]="isRequired"  style="width: 100%">
      <md-option *ngFor="let type of types" [value]="type.typeId" [disabled]="type.disabled">
            {{ type.typeName }}
     </md-option>

Any help would be appreciated. Thanks in advance!


Solution

  • You didn't posted whole code but I will try to help you without it. First of all, you don't need ngModel if you have a formControl on it. It's basically do the same thing - 2 way data binding.

    this.testService.getTypes()
        .subscribe(result => {
            if (result.code === 200) { 
                this.types = result.data; 
                this.form.controls['typeName'].setValue(this.types[0].typeId); //add this line                     
            }
        }, error => {
            this.router.navigate(['signin']);
        });